Use the JVM
Profiler Interface for accurate timing -
JavaWorld
Tutorial Details:
Java Tip 92: Use the JVM Profiler Interface for accurate timing
Java Tip 92: Use the JVM Profiler Interface for accurate timing
By: By Jesper Gørtz
Improve performance analysis by measuring Java thread CPU time
he textbook approach to simple performance analysis is to call System.currentTimeMillis() before and after the code to be measured. This is comparable to using a stopwatch when testing GUI activity, and works fine if elapsed time is really what you want. The downside is that this approach may include much more than your code's execution time. Time used by other processes on the system or time spent waiting for I/O can result in inaccurately high timing numbers.
Trouble with threads
Programming languages like C and Pascal must use operating system calls to get the CPU time spent by a thread or process. Java applications can do this too, by using native, and therefore unportable, methods. Unfortunately, the results for an OS thread may not be directly related to the executing Java thread. This is because the way Java threads are mapped to OS threads is entirely up to the JVM -- and different JVMs use different strategies.
Some JVMs use green threads, which run all the Java threads in one native OS thread (a so-called n-to-one mapping). The HotSpot JVM uses native threads, which may execute in parallel on a multi-CPU machine. The fact that several threads are executing in parallel means that the sum of the CPU times may exceed the elapsed real time. On Solaris, Java threads are not bound permanently to the same native threads but are remapped by the scheduler (in an n-to-m mapping). So, getting the CPU time for the current native thread does not give you the time you want. Contrast this with the Blackdown port of the JDK 1.2 to Linux, where a thread is akin to a process ( one-to-one mapping).
The result of the JVM successfully hiding the underlying machine and operating system means that the native information is often useless to Java programmers. Fortunately, each JVM knows how it maps threads, even if this detail is hidden from the application programmers. Java 2 introduced a new API -- the Java Virtual Machine Profiler Interface (JVMPI) -- that allows access to the necessary timing information.
The Profiler Interface
The JVMPI is a C interface to the JVM, where profilers may access the state of the JVM via an in-process native agent, and can be notified of interesting events like object allocations and method invocations. You can use the JVMPI with a frontend that provides a GUI, like commercial profilers OptimizeIt or JProbe, or the agent can simply dump the profiling information into a file like HPROF (see Resources for more information).
Profilers are very good at identifying hot spots that need to be optimized. They work either by sampling or by instrumentation, meaning by tracing method invocations or by modifying class code on class loading. Sampling has little overhead but is very coarse-grained, whereas instrumentation has a significant overhead and may get in the way of optimization, especially because Java programs typically have many small methods.
A potential problem is that the profiler itself uses CPU and memory resources. The latter may affect execution of the program with respect to hardware caching and OS swapping of virtual memory, causing the timing information to get blurred. This is not a serious problem for profiling in which you are interested in the big picture and looking at relative figures, but if you want to microbenchmark JVMs, components, code snippets, or algorithms, you must choose another approach that has less overhead.
The JVMPI provides a function, GetCurrentThreadCpuTime() , which returns the CPU time in nanoseconds for the current Java thread. It does this no matter which technique you use to map Java threads to OS threads. Despite the nanosecond resolution, the function is not more precise than the underlying operating system. On Windows NT it works in 10 millisecond increments. An extremely simple profiler agent with the ability to access this information consists of the following C++ code:
#include
// global jvmpi interface pointer
static JVMPI_Interface *jvmpi_interface;
extern "C" {
// profiler agent entry point
JNIEXPORT jint JNICALL
JVM_OnLoad(JavaVM *jvm, char *options, void *reserved) {
// get jvmpi interface pointer
if ((jvm->GetEnv((void **)&jvmpi_interface, JVMPI_VERSION_1)) < 0) {
return JNI_ERR;
}
return JNI_OK;
}
JNIEXPORT jlong JNICALL
Java_dk_capgemini_tc_JProf_getCurrentThreadCpuTime(JNIEnv *, jclass) {
// return 0 if agent not initialized
return jvmpi_interface == 0 ? 0 :
jvmpi_interface->GetCurrentThreadCpuTime();
}
}
This function may be called from a Java program using JNI via the following class:
package dk.capgemini.tc;
public class JProf {
public static native long getCurrentThreadCpuTime();
static { System.loadLibrary("capjprof"); }
}
The capjprof.zip file ( Resources ) accompanying this tip contains the source code and make files for Solaris and Windows NT. The resulting DLL or shared object must be put in the library path for the JVM to find, and the JVM must be told to use it with an application.
java -Xruncapjprof application
The -Xrun option enables the profiler by instructing the JVM to call JVM_OnLoad() in the capjprof library. If you run the application without this option, JProf.getCurrentThreadCpuTime() will return 0.
Comparing collection indexing
You can try this out with a comparison of indexing into an array , an Arrays.asList , a ListArray , and a Vector . First you need a helper class to support the microbenchmark:
class Prof extends dk.capgemini.tc.JProf {
String me;
long time, cputime;
Prof(String name) {
me = name;
}
void start() {
cputime = getCurrentThreadCpuTime();
time = System.currentTimeMillis();
}
void stop() {
cputime = getCurrentThreadCpuTime() - cputime;
time = System.currentTimeMillis() - time;
}
void print() {
System.out.println(me + " time: " + time + " ms"
+ " cputime: " + cputime/1000000 + " ms");
}
}
The methods to be measured index a number of times and assign the result to a variable so that the loop is not optimized away. Below is the Vector indexing. The other methods look the same except for the type of the collection list parameter.
void index(int n, Vector c) {
Object o;
for (int i=0; ifor (int j=0; jo = c.get(j);
}
}
}
The main method creates the collections with the same contents and makes the comparisons (see capjprof.zip for the full source). The application takes a number of optional parameters controlling the number of elements in the collection (default is 1,000), the number of times to loop (default is 10,000), and whether the methods should be called in sequence or in parallel (default is in sequence).
java -Xruncapjprof performance.CollIndex [elements 1000] [times 10000]
[threads]
My single-processor Windows NT with JDK 1.2.2 using the JIT produces the following results, which show that you should avoid unnecessary synchronization in Vector , because a simple array is much more efficient.
Indexing collection 1,000 elements 10,000 times in sequence
Test
Stopwatch time (ms)
JVMPI time (ms)
Vector
3,074
3,034
ArrayList
872
841
asList
951
891
array
70
70
With JDK 1.3 RC1, the figures indicate that synchronization has become much more efficient with HotSpot.
Indexing collection 1,000 elements 10,000 times in sequence
Test
Stopwatch time (ms)
JVMPI time (ms)
Vector
1,262
1,211
ArrayList
1,202
1,201
asList
681
640
array
170
170
The reason ArrayList does not perform better than Vector here is that ArrayList.get() contains sloppy code. Make your own version with a better range check if performance matters. Just for fun, try to run the measurements in parallel in separate threads and note the difference in elapsed time and CPU time.
Indexing collection 1,000 elements 10,000 times in parallel
Test
Stopwatch Time (ms)
JVMPI Time (ms)
Vector
3,325
1,271
ArrayList
3,095
1,201
asList
1,953
630
array
531
160
Conclusion
In this tip, I demonstrated how to utilize the JVMPI to measure execution time and discussed why this approach is best for microbenchmarking.
However, there are still problems. An optimizing JVM like HotSpot may fool you with microbenchmarks because overly simple code may escape optimization or be totally eliminated.
Additionally, the garbage collector may interfere and use time in a entirely JVM-dependent manner. With JDK 1.2.2, the garbage collection is done in the user thread, whereas a system thread does the work with HotSpot. Under HotSpot, the incremental garbage collection cannot run when using an active profiler agent. You can influence the behavior of the garbage collector by calling System.gc() and by setting initial and maximum heap size when starting the JVM.
This page formated for crawlers and browsers that don't support scripts and tables.
Home
EZone
Read
Tutorial at: Click here to view the tutorial
Rate Tutorial: Use the JVM
Profiler Interface for accurate timing -
JavaWorld
View Tutorial: Use the JVM
Profiler Interface for accurate timing -
JavaWorld
Related
Tutorials:
|
Displaying 1 - 50 of about 2753 Related Tutorials.
|
Open Source JVM
Open Source JVM,free java virtual machine,free jvm,jvm free
Open Source JVM
Java Virtual Machine or JVM
for short is a software... of Open Source JVMs.
Wonka -- an open source embedded JVM |
How Accurate is GPS?
How Accurate is GPS?
How Accurate is GPS... for civilian use.
GPS works in all weather conditions and all over the world. GPS does... for this.
How Accurate is it?
The new generation of GPS |
Class or Interface
Java: Class or Interface
Java NotesClass or Interface
Declare variables as class or interface type... the methods defined in the
List interface, it would be better to do the
following |
Interface in JSP
are going to make use of interface
in our jsp application.
The code...
Interface in JSP
Interface in JSP...;
In interface none of its methods are implemented. All |
Interface in Java
Interface?" and "Why to use Marker Interface?" and "...
Marker Interface,Java Marker Interface
Interface...;
In this section we will learn about Interface and Marker |
Basics of Global Positioning System
Positioning System is originally a part of Navigation System with Timing and Range... to monitor all kinds of GPS activities. GPS receivers use triangulation technique in which the area is divided into a series of triangles for accurate 3D measurements |
MySQL User Interface
MySQL User Interface
MySQL User Interface...;
In this section you will read how to define the function Interface... defined function) interface.
These are complied as object files. After |
Factors responsible for GPS signal errors
highly accurate GPS signals (military related) from public use as these can... of signal delay. Calculating accurate co-ordinates of an object primarily depends... – The receiver enabled with a clock that is not as accurate as the atomic |
SortedMap (interface) example in java Collection Framework
I will show you how you can use SortedMap interface in your Java
application... (interface) example in java Collection Framework
 ... in the section on Object Ordering In addition to the normal
Map operations, the Map interface |
GPS Tracking Map
, tracking, navigating, mapping and timing. So mostly this technology is widely... the use of a computer aided drafting (CAD) program. Any particular place... and longitude, these provide more accurate information, so that the GPS software |
Class and Interface Concepts
Java: Class and Interface Concepts
Java: Class and Interface Concepts
Class and Interface Concepts..., the method
in the superclass is overridden. A common use |
What is the use of java?
(JVM)
The Java Application Programming Interface (API)
The Java...
What is the use of java?
What is the use... it is easier to use than C++ and works on the concept of object-oriented
programming |
Sources of GPS Error
and development work is still going on to develop more and more accurate systems, it would... in clock of the GPS receiver is not as accurate as the atomic clocks of the satellites and the slight timing errors leads to corresponding errors in calculations |
Linux as a Command Line Interface (CLI) Vs. Graphics User Interface (GUI).
Linux as a Command User Interface (CUI)
Linux as a Command Line Interface (CLI) Vs. Graphics User Interface (GUI...: command line and graphical. Command line shells provide a command line interface |
How to set memory used by JVM in Ant
How to set memory used by JVM in Ant
How to set memory used by JVM in Ant
 ... to set memory size of JVM (java virtual
machine), when ANT (another neat tool |
Kilometers to Miles - User Interface Only
Java: Example - Kilometers to Miles - User Interface Only... Interface Only
This program produces a user interface.../KmToMilesNoModel.java - Input field, button, output field
// This is the user interface |
Collection Interface
Java: Collection Interface
Java NotesCollection Interface
The Collection interface is the parent of the
List and Set interfaces, but not Map.
Assume the following declaration |
Collection Interface
Java: Collection Interface
Java NotesCollection Interface
The Collection interface is the parent of the
List and Set interfaces, but not Map.
Assume the following declaration |
User Interface Design
Java: User Interface Design
Java NotesUser Interface Design
Links
Sun's Java Look and Feel Design... to start.
AskTog - www.asktog.com
User Interface Design for Programmers - Joel |
Set interface
Java: Set<E> interface
Java: Set<E> interface
Only one. Sets are collections...; interface is a subinterface of Collection<E>.
There are two very useful concrete |
Get Thread Name
. The JVM
provides an application to execute the multiple thread running...)A GetThreadName implements the Runnable interface, that provides you to
execute |
Peculiarities of Java ...
on one platform can run on any platform provided the platform
must have the JVM. .... Programs are easy to write and debug because java
does not use the pointers... language robust.
Secure: Java does not use memory pointers
explicitly. All |
Search Engine Interface
Search Engine Interface, Developing Search Engine Interface
Search Engine Interface
 ... will describe about the search and index interface of our
search engine |
Examine Interface Example
Examine Interface Example
Examine Interface...;?
To know that given class is an Interface or Class we
can use boolean method isInterface() which returns true
if given class is an Interface |
How to use KeyListener
Keylistener Java,How to use KeyListener,Java Keylistener Example
How to use KeyListener
 ... are handled through the KeyListener
Interface that has been implemented in the main class |
Open Source FTP
reading some of the comments for the blog entry, OK is pretty much accurate. I... is all that I'll use (FTP ain't safe).
 ... to be easy to use, fast and reliable. It is compatible with most current versions |
Open Source Profilers written in Java
|
Java: Interfaces
likely to use an interface than define it.
Here is what...: Interfaces
An interface is a list of methods that must be defined by
any class which implements that interface.
It may also define constants (public static |
Use of tag of jstl
Use of <sql:transaction> tag of jstl
Use of <...;
javax.sql.DataSource interface.
driver
driver
class name that is use to create connection |
Java error class interface or enum excepted
java error class interface or enum excepted
Java error class interface or enum excepted
 ... class interface or enum excepted are the class of java error that occurred
when |
History of web application
its own client program and it worked as a user interface and need to be
installed on each user's personal computer. Most web applications use
HTML/XHTML... and the Servlets.
Common Gateway Interface (CGI)
The Common Gateway Interface |
Use if in velocity
Use if in velocity
Use if in velocity
 ...;
This example shows you how
to use if statement in velocity. Description |
Old and New Vector Methods
was updated to implement the List interface.
Use the List methods because they are
common to other data structure. If you later decide
to use something other...), the
language had not entirely changed to use the new Collections methods. For example |
GUI Alternatives
should your interface be in Java? You can use existing GUI technologies
like..., it isn't difficult to build a Graphical User Interface (GUI) in Java...: Mix logic and interface.
This is a typical style for small student |
Java: Text
Java: Text
Java: Text
If you work with text, you need to know about the following
user interface text... of formatted documents, you might use
JEditorPane (for displaying plain, HTML |
Example - Calc GUI
- Calc Extensions
This is the source for the graphical user interface of a simple... ActionListener to use for all operator buttons.
ActionListener opListener... operator buttons.
// Use array of button names to create buttons |
Using the Prepared Statement Twice
;
This JDBC tutorial helps us to use the PreparedStatement
interface of java.sql package twice in a program. According to our
requirement we can use the PreparedStatement object. The PreparedStatement object represents |
Java Interview Questions 3
interface?
Answer: When you use Serializable interface, your class.... When you
use Externalizable interface, you have a complete control over your... many methods in the Serializable interface?
Answer:There is no method |
Java Interview Questions - Page 5
your class "implements" Runnable interface. Put jobs
in a run... object be locked down for exclusive use by a given thread?
Answer... of the Thread class, the JVM invokes the thread's run()
method when the thread |
How to use this keyword in java
in Java
How to use "this" keyword in java... and local variables same. Now to avoid the confliction between
them we use... of the program for the illustration of how to what is this
keyword and how to use |
Use if and elseif statements in velocity
Use if and elseif statements in velocity
Use if and elseif statements in velocity
 ...;
This Example shows you how
to use |
Use Group Class in SWT
Use Group Class in SWT
Use Group Class in SWT
 ...;
In this section, you will learn how to use Group class |
How to use Map in velocity
How to use Map in velocity
How to use Map in velocity
 ...;
This
Example shows you how
to use map in velocity |
How to use List in velocity
How to use List in velocity
How to use List in velocity
 ...;
This
Example shows you how
to use List in velocity |
Define and use Macro in Velocity
Define and use Macro in Velocity
Define and use Macro...;
This
Example shows you how
to define and use macro in velocity template and also shows how
to use Iterator in velocity  |
How to handle the text using Key Listener Interface
How to handle the text using Key Listener Interface
How to handle the text using Key Listener Interface... Interface. In the given example, we are going to show you how to
display the text |
Understanding Data Source
and Directory interface) naming service so application can use the JNDI API... the DataSource interface as an alternative to the DriverManager for establishing... protocol use to communicate with the server the name of the database and so |
Use Log in Servlet Context
Use Log in Servlet Context
Use Log in Servlet Context
 ...;
This section illustrates you how to use log in Servlet Context.
We |
Use of "descendant" in XPath expression
Use of "descendant" in XPath expression
Use... in Java tutorial you will
learn use of descendant in XPath expression. "... and creates a Document object. Next we have created XPath object
with the use |
Use of "parent" in XPath expression
Use of "parent" in XPath expression
Use of "parent... you have studied
how to use child axis in XPath expression . Now this section will describe
the use of "parent" axis. "parent" axis |
|
|
|