I want to calculate how much CPU time my function takes to execute in Java. Currently I am doing as below.
long startTime = System.currentTimeMillis();
myfunction();
long endTime = System.currentTimeMillis();
long searchTime = endTime - startTime;
But I found out that for the same I/P I get different time depending on system load.
So, how to get exact CPU time my function took to execute.
System.currentTimeMillis()
will only ever measure wall-clock time, never CPU time.System.nanoTime()
is often more precise (and never worse) than currentTimeMillis()
.ThreadMXBean.getThreadCPUTime()
can help you find out how much CPU time a given thread has used. Use ManagementFactory.getThreadMXBean()
to get a ThreadMXBean
and Thread.getId()
to find the id
of the thread you're interested in. Note that this method need not be supported on every JVM!