Calculating CPU time and Wait Time

Viewed 33

To calculate ideal ThreadPool size in my project I have to calculate CPU time and Wait time for a thread. So I have made a dummy project something like this:

class  ThreadClass extends Thread
{
    public static Long total;
    public void run()
    {
        try
        {
            Long start=System.currentTimeMillis();
            System.out.println("Starting at "+start);
            //Thread.sleep(1000);
            System.out.println("thread is running...");
            Long end=System.currentTimeMillis();
            System.out.println("Ending at "+end);
            total=end-start;
            System.out.println("Total "+total);
        }
        catch (Exception e){}
    }
}
public class Main3 {
    public static void main(String[] args) {
        ThreadClass t=new ThreadClass();
        t.start();
        Long tid=t.getId();//currentThread() still showing same
        ThreadMXBean threadMXBean= ManagementFactory.getThreadMXBean();
        long cpuTime = threadMXBean.getThreadCpuTime(tid)/1000000;
        System.out.println("CPU time calculated in MAIN "+cpuTime);
    }
}

The Value I am getting : Starting at 1662975991279 thread is running... Ending at 1662975991319 Total 40 CPU time calculated in MAIN 222

Now my question is isn't the "Total" value is wait time + cpu time? Or is it the wait time only? And for this simple code why CPU time is 222 MS and how come this is higher than "Total"??

Am I calculating correctly the CPU time and Wait time?

1 Answers

Total should be wait+cpu time. I guess your total thread time is short enough you might measure nothing, so at least the Thread.sleep() should help on total time.

For the total, somehow I believe you are comparing the ThreadClass thread vs the main/default thread. Compare these two lines:

Long tid=t.currentThread().getId();

Long tid = t.getId();

Since the code is getting executed in the main thread, t.currentThread() returns the main thread where you intend to measure t.

Related