CPU time vs Wall clock time
845379Mar 7 2011 — edited Mar 8 2011Hi all,
I want to measure CPU time and wall clock time of a code section.
import java.lang.management.*;
import java.util.*;
public class MeasureProcessTime {
public static long getCpuTime( ) {
ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
return bean.isCurrentThreadCpuTimeSupported( ) ?
bean.getCurrentThreadCpuTime( ) : 0L;
}
public static long getUserTime( ) {
ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
return bean.isCurrentThreadCpuTimeSupported( ) ?
bean.getCurrentThreadUserTime( ) : 0L;
}
public static int Fib(int n)
{
if (n == 1 || n == 2)
return 1;
else
return Fib(n-1) + Fib(n-2);
}
public static void main(String[] args)
{
try
{
long startTm = System.nanoTime();
//Thread.sleep(2000);
Fib(30);
long endTm = System.nanoTime();
System.out.println("CPU time = " + getUserTime()/1000000 + " milliseconds");
System.out.print("Wall clock time = " + (endTm - startTm)/1000000);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
However, the result is always CPU time > wall clock time..
CPU time = 78 milliseconds
Wall clock time = 5
What is the error? I my understanding, CPU time should be less than or equal to wall clock time.
Thanks.
Wenbin
Edited by: user13827934 on 2011-3-7 上午6:30