Profile-guided Optimization (PGO), profile-guided optimization (PGO), enables compilers to optimize for internalization and code layout, with free performance gains, by generating profiles based on piling or sampling from a program’s runtime. There are few tutorials to use on Android, and there are some problems with the actual operation. Here is a note of how to use the pilings.

1. Use-fprofile-generateCompile and link the pile-in dynamic library

Adding compile parameters

android {
    ...

    defaultConfig {
        ...
        
        externalNativeBuild {
            cmake {
                cppFlags '-std=c++11 -fprofile-generate'}}}}Copy the code

2. Run representative processes to collect configuration files

In Android, you need to manually call __llvm_profile_write_file at the end of the configuration file generation. In C++, you need to add extern “C” or the method will not be found in the link

extern "C" {
extern int __llvm_profile_write_file(void);
}
Copy the code

Before loading the dynamic library, set the environment variable LLVM_PROFILE_FILE to specify the location where the configuration file is generated

static {
    try {
        Os.setenv("LLVM_PROFILE_FILE"."/path/to/%m.profraw".true);
    } catch (ErrnoException e) {
        e.printStackTrace();
    }
    System.loadLibrary("native-lib");
}
Copy the code

LLVM_PROFILE_FILE You can use the following modifiers to set the profile path

  • % p process ID
  • %h hostname
  • %m Unique profile name

If the following error occurs

java.lang.UnsatisfiedLinkError: dlopen failed: cannot locate symbol "__start___llvm_prf_vnds" referenced by "... .so"
Copy the code

You need to change the link program to LLD or Gold. The NDK R22 already uses LLD by default. You can also upgrade the NDK to R22

android {
   ...
   
   ndkVersion '22.1.7171670'
}
Copy the code

Use 3.llvm-profdataMerge the transformation profile

If you have multiple configuration files, merge and transform them using the following commands

$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-profdata \ merge --output=pgo_profile.profdata \ 
      
Copy the code

Use this command to convert the format even if there is only one configuration file

4. Compile using the configuration file

android {
    ...

    defaultConfig {
        ...
        
        externalNativeBuild {
            cmake {
                cppFlags '-std=c++11 -fprofile-use=/path/to/<>.profdata'
            }
        }
    }
}
Copy the code

The configuration file can also be used after the code changes, and the compiler generates a -wprofile-instr-out-of-date warning if it cannot be used any more

reference

  1. Profile guided optimization for native Android applications

  2. Optimization with Configuration File Boot (PGO)

  3. How to compile with Profile Guided Optimization (PGO)