0

I'm working in a code in java which I must send to an external computer to run. So far in my computer I was using this function to get an idea of time (real time was enough until now)

     long start;
     long end;
    start = System.currentTimeMillis();
    //
    %code
    //
    end   = System.currentTimeMillis();
    time=(float) ((end - start)/1000.);

But then I realized, the computer distribute the CPU time expended among the users, so the execution is "paused" several seconds until is the turn of my run again, therefore I get a time which is not accurate. I investigated and implemented this example based on the answer of Recording Program's CPU Time :

    try {

       ThreadMXBean thread = ManagementFactory.getThreadMXBean();

       long cpu = thread.getCurrentThreadCpuTime();
       long user= thread.getCurrentThreadUserTime() ;
       Thread.sleep(300);
       int i=0;
       while(i<100000){
           System.out.println("hola");
           i++;
       }
       cpu =( thread.getCurrentThreadCpuTime() - cpu ) ;
       user=( thread.getCurrentThreadUserTime() -user );
       System.out.println("Cpu:"+cpu);
       System.out.println("User:"+user);
   }
   catch (InterruptedException _) {}

for example I've gotten these results:

Cpu:1218750000 > User:593750000

Cpu:1453125000 >User:750000000

is thread.getCurrentThreadUserTime() the function I need for my case?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38

1 Answers1

0

I have never used this ThreadMXBean although it would have been useful sometimes in the past :)

Anyway, the JavaDoc tells

long getCurrentThreadUserTime()

Returns the CPU time that the current thread has executed in user mode in nanoseconds. The returned value is of nanoseconds precision but not necessarily nanoseconds accuracy. This is a convenient method for local management use and is equivalent to calling:

getThreadUserTime(Thread.currentThread().getId());

Returns: the user-level CPU time for the current thread if CPU time measurement is enabled; -1 otherwise. Throws: UnsupportedOperationException - if the Java virtual machine does not support CPU time measurement for the current thread. See Also: getCurrentThreadCpuTime(), isCurrentThreadCpuTimeSupported(), isThreadCpuTimeEnabled(), setThreadCpuTimeEnabled(boolean)

So what you are doing seems to be correct. You may ask yourself why the numbers are so high, they are returned in nanoseconds.

mambax
  • 1,079
  • 8
  • 17