Published on

How to Profile Android Apps with Open-Source Tool

Authors
  • avatar
    Name
    Almaz Khalilov
    Twitter

How to Profile Android Apps with Open-Source Tools

Profiling mobile apps is essential for improving performance and user experience. By using open-source tools, you can identify issues like high CPU usage, memory leaks, and slow network activity. Here’s how you can start:

  • Key Tools: Use Android Studio Profiler, Perfetto, and Systrace to track CPU, memory, and network performance.
  • Setup Basics: Make your app profileable by updating your AndroidManifest.xml, enable system tracing, and configure tools for local Australian settings (e.g., DD/MM/YYYY date format, 24-hour time).
  • Performance Metrics:
    • CPU: Identify tasks causing delays and offload them to background threads.
    • Memory: Fix leaks and optimise image loading.
    • Network: Test API response times and improve data transfer rates.
  • Australian Context: Tailor configurations for local formats, network conditions, and devices.

Profiling ensures your app runs smoothly, consumes less battery, and delivers a better experience for users across Australia.

Actionable app profiling in Android Studio

Prepare Your Profiling Tools

Getting your profiling tools set up correctly is key to capturing accurate performance data. For Android apps, use tools like Android Studio Profiler, Perfetto, and Systrace to analyse and optimise your app's performance.

Set Up Android Studio Profiler

Start by downloading Android Studio Hedgehog from developer.android.com. Once installed, follow these steps:

  1. Open your project and update your AndroidManifest.xml file by adding this line to make your app profileable:

    <profileable android:shell="true" />
    
  2. Adjust local time settings in Android Studio to align with Australian formats (e.g., DD/MM/YYYY; AEST/AEDT).

Android Studio Profiler is a great starting point for tracking app performance. It provides detailed information about CPU usage, memory allocation, network activity, and energy consumption, making it invaluable during development and debugging. For deeper system-level insights, you'll need to configure Perfetto.

Install Perfetto for System Tracing

Perfetto offers a system-wide view of your app's performance. Here's how to set it up:

  1. Enable Developer Options on your device.
  2. Turn on USB debugging and System Tracing.
  3. Open perfetto.dev in Google Chrome.
  4. Configure the trace settings:
    • Buffer size: 100MB (recommended for detailed traces)
    • Duration: 5–30 seconds
    • Categories: Include CPU scheduling, memory usage, and network activity

For Australian-specific profiling needs, consider these configurations:

Setting TypeRecommended Configuration
Time FormatDD/MM/YYYY HH:MM:SS
Buffer Size100MB for detailed analysis
Trace Duration10 seconds for quick tests, 30 seconds for in-depth profiling
Network AnalysisEnable mobile network metrics

Perfetto is particularly useful for tracking system-level issues, offering insights that go beyond app-level profiling.

Set Up Systrace Tool

For a more granular look at system performance, Systrace is an excellent tool. It requires Python and provides detailed data on UI performance and rendering. Follow these steps to set it up:

  1. Install Python 3.x on your development machine.

  2. Navigate to the Systrace directory in your Android SDK:

    cd android-sdk/platform-tools/systrace/
    
  3. Install the required Python dependency:

    pip install pyserial
    
  4. Run Systrace with the following command, replacing your.package.name with your app's package name:

    python systrace.py -t 10 -a your.package.name sched gfx view
    

Systrace is especially effective for pinpointing UI jank and rendering problems, ensuring that your app delivers a smooth and seamless experience for users.

Profile Apps with Open-Source Tools

Learn how to measure key performance metrics using open-source tools to optimise your app's performance.

Measure CPU Usage

To monitor native CPU performance, you can use Simpleperf. Here's how:

simpleperf record -p YOUR_APP_PROCESS_ID --duration 30
simpleperf report --children

Focus on these CPU metrics during analysis:

MetricWhat to Watch ForHow to Address It
Main ThreadTasks exceeding 16ms disrupt smooth animationsOffload heavy tasks to background threads
Background TasksHigh CPU usage during background operationsOptimise algorithms to reduce unnecessary overhead
Garbage CollectionFrequent collections signal inefficient memory useReduce allocations and use object pooling if needed

Use flame graphs to identify bottlenecks, such as slow function calls. Once CPU performance is addressed, move on to memory profiling.

Check Memory Usage

The Memory Profiler in Android Studio is an excellent tool for identifying memory-related issues like leaks. Follow these steps:

  1. Trigger garbage collection before starting your recording.
  2. Record memory allocations during specific user interactions.
  3. Capture heap dumps during or after unexpected memory spikes.

Here are common memory challenges and their solutions:

ComponentWarning SignsWhat You Can Do
RecyclerViewRetention of ViewHoldersEnsure proper recycling of list items
Jetpack ComposeToo many recompositionsUse remember() and derivedStateOf() effectively
ImagesGradual increase in heap sizeUse efficient image loading and bitmap pooling

Once you've fine-tuned memory usage, it's time to evaluate network performance.

Test Network Speed

To analyse network activity, Perfetto is a reliable tool. Run the following command:

perfetto -c network_trace_config.pb -o trace.perfetto-trace

When assessing network performance, pay attention to these key factors:

MetricWhy It MattersHow to Improve It
API Response TimeSlow responses hurt user experienceUse caching to reduce load times
Data Transfer RateConsistent speeds are crucialCompress payloads to improve transfer efficiency
Connection TimeDelays in establishing connections affect speedImplement connection pooling for faster responses

Testing under different network conditions, especially those reflecting Australia's diverse regions, ensures your app performs well across various scenarios. These profiling techniques help refine your code, leading to smoother animations and better overall responsiveness.

Cybergarden incorporates these methods into agile workflows, ensuring apps meet high standards for quality and user experience.

Read and Apply Profiling Results

Once you've gathered profiling data, the next step is understanding and applying those insights to improve your mobile app's performance. This includes tackling issues like screen stutters, battery drain, and setting performance benchmarks.

Fix Screen Stutters

Screen stutters can ruin the user experience. Tools like Systrace help pinpoint frame drops that cause these interruptions. Here's a quick example:

Performance IssueSystrace IndicatorSuggested Fix
Frame DropsRed bars in UI threadShift heavy computations off the main thread

Pay close attention to frames that take longer than 16.67ms in the Systrace output - these are the ones responsible for visible stutters.

Reduce Battery Usage

Battery drain is another common pain point. Android's Energy Profiler is a great tool to identify CPU spikes that impact battery life. Here's how to approach it:

  • Record the app's baseline energy usage when idle.

  • Monitor for unusual CPU activity during user interactions.

  • Use the following command to check detailed battery stats:

    adb shell dumpsys batterystats
    

This approach helps you pinpoint and address areas where your app might be unnecessarily taxing the battery.

Make Baseline Profiles

Baseline profiles, introduced in AGP 8.0+, can significantly improve app start times and optimise performance by focusing on critical execution paths. To implement them, use the Android Gradle Plugin and evaluate their effectiveness with Android Studio's CPU Profiler.

At Cybergarden, we've seen clear improvements in our app performance after integrating baseline profiles - especially in start-up speed and responsiveness. It’s a step worth considering to give your users a smoother experience.

Australian Developer Settings

When profiling mobile apps in Australia, it's essential to configure your tools to align with local standards. Here's how to properly set up your profiling environment.

Configure Memory Units

Australian developers should ensure their profiling tools display memory measurements using the metric system. In Android Studio Profiler, set memory usage to be shown in MB and GB with appropriate decimal formatting:

Memory DisplayAustralian FormatExample
Small ValuesMB with commas1,024.5 MB
Large ValuesGB with commas2.5 GB
System MemoryGB with two decimals16.00 GB

To update these settings in Android Studio, navigate to File > Settings > Memory View and select the metric display option. This ensures consistency with Australian conventions, making memory profiling data easier to interpret. Once that's done, move on to adjusting time and date settings.

Set Time and Date Format

Australia uses a unique date and time format compared to other regions. To align your profiling tools with local standards, configure them as follows:

  • Date format: DD/MM/YYYY
  • Time format: 24-hour clock

To adjust these settings in Android Studio:

  1. Open File > Settings (or Android Studio > Preferences on macOS).
  2. Navigate to Appearance & Behaviour > System Settings.
  3. Set the region to "Australia".
  4. Ensure the date format displays as DD/MM/YYYY.

This setup ensures your timestamps and performance logs follow Australian conventions, making it simpler to track issues and share reports with local teams.

Update Language Settings

For consistency in spelling and terminology, set your development environment to Australian English. This affects technical terms (e.g., "optimise" instead of "optimize"), system messages, and exported documentation.

To update the language settings in Android Studio:

  1. Go to File > Settings > Appearance & Behaviour.
  2. Select System Settings > Language.
  3. Choose English (Australia) from the dropdown menu.
  4. Restart Android Studio to apply the changes.

Summary

Using open-source profiling tools is a smart way to ensure mobile apps perform well for Australian users. These tools help identify and fix issues that could negatively affect the user experience.

Key Performance Benefits

Profiling delivers clear advantages:

AspectImpact on Australian UsersOptimisation Focus
Network PerformanceHandles different connectivity speeds in urban and regional areasFaster response times
Battery UsageDesigned for longer use, even in tough conditionsLower battery consumption
App ResponsivenessEnsures smooth operation across various devicesEnhanced interactivity

Three main areas to prioritise:

  • Regular Performance Monitoring: Continuously profile during development to spot and fix issues early.
  • Local Conditions Testing: Simulate varied network environments to maintain steady performance.
  • Device Optimisation: Focus on improving launch speed, memory usage, and battery life.

FAQs

How can I set up profiling tools to reflect Australian date and time formats?

To make sure profiling tools are properly set up for the Australian context, you’ll need to tweak the settings to reflect local standards. Most tools let you adjust date and time formats - set dates to DD/MM/YYYY and use the 24-hour clock where it's an option.

Also, double-check that your system or app's locale is configured to en-AU. This helps ensure things like currency symbols and number formats follow Australian conventions. If the tool offers automated localisation, selecting Australia as the region should automatically apply these settings.

What are some key signs of performance issues in mobile apps that can be detected using open-source profiling tools?

Performance problems in mobile apps often show up as sluggish loading times, heavy memory usage, rapid battery drain, or unresponsive interfaces. To tackle these challenges, developers can turn to open-source profiling tools, which analyse key metrics like CPU usage, memory allocation, and network activity.

For instance, if CPU usage is unusually high, it might point to inefficient code or unnecessary background processes. Similarly, examining memory allocation can uncover memory leaks that could lead to app crashes or gradual slowdowns. By leveraging this data, developers can fine-tune app performance and deliver a smoother, more reliable user experience.

How can I fix battery drain issues found during app profiling to improve the experience for Australian users?

To tackle battery drain issues revealed during app profiling, start by diving into the profiling data to identify areas draining the most energy. Common culprits might include excessive background processes, frequent location updates, or inefficient network requests. Address these by cutting down on unnecessary background activity, batching location updates, or streamlining API calls.

It’s also crucial to test your app in real-world Australian conditions. Think about challenges like fluctuating network speeds or high temperatures, which can impact performance. Incorporating energy-saving strategies, such as adaptive refresh rates or refining code for efficient resource use, can improve both battery life and the overall user experience. Keep an eye on your app’s performance over time with regular monitoring and updates to ensure it stays efficient.