CPU execution time in Java

前端 未结 5 1929
我寻月下人不归
我寻月下人不归 2020-12-03 03:44

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();
           


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 04:18

    1. System.currentTimeMillis() will only ever measure wall-clock time, never CPU time.
    2. If you need wall-clock time, then System.nanoTime() is often more precise (and never worse) than currentTimeMillis().
    3. 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!

提交回复
热议问题