How to do Java Application's CPU Profiling using Java VisualVM to figure out where most of the time is spent by a Java program.
CPU Profiler works by taking thread dumps of the system at some regular interval (if using Sampling Profiler) and reporting on where it observes time being spent. This will allow developers to focus on the parts in their applications where most of the execution time is spent and try to optimize such problem areas by taking appropriate corrective actions.
The sampling rate is configurable. Other option is Tracing Profiler but it may cause more performance overheads.
Path of Java VisualVM- <JAVA_HOME>/bin/jvisualvm.exe
Open Java VisualVM and make sure to install Profiler Plugin from the Available Plugins
tab. Once installed, The plugin should be listed in the Installed
tab as shown in below screenshot-
Now open the Profile Startup
setting window from the Application
-> Profile Startup
menu.
Things to note-
- Use an available port number on your system for attaching the profiler to your app to be profiled
Start Profiling From Classes
section should your application classes or packages
Now copy the generated JVM parameters by clicking on Copy to Clipboard
button.
Now go to Eclipse Run Configurations and paste the copied JVM arguments to the VM Arguments
section as shown below; save and run the app.
If you get the error code 62, then do this-
CPU Profiling Fails With "Redefinition failed with error 62"
Resolution: Restart the application with the VM argument -Xverify:none to disable classfile verification.
After this app run terminates, you would be prompted by Java VisualVM to save the snapshot of this run. Save the snapshot and view it by selecting it. This should look as shown below-
Now you can see how much time was spent in each of the methods in the call tree.
It is advised that you don't run profiling in production and other higher version as byte code instrumentation has some overhead. So, care must be taken to run profiling on your development workspace only.
This profiler can be used to do memory profiling as well simply by selecting Memory
profiling while setting Application Profile options.