有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java记录程序的CPU时间

我想记录我的Java程序所用的时间。大多数论坛建议:

int starttime=System.nanoTime();  
//program code  
int endTime=System.nanoTime();  
int timetaken=starttime-endTime;  

这种方法的问题在于,如果有多个程序在运行,那么endTime和starttime之间的差异并不是我的程序所用的时间。它也是在CPU中调度不同程序所花费的时间。然而,我只对记录我的程序所花费的时间感兴趣。这次我该怎么办


共 (1) 个答案

  1. # 1 楼答案

    你可以在这个article中找到答案。 引用这篇文章:

    Call ManagementFactory . getThreadMXBean() to get a ThreadMXBean that describes current JVM threads. The bean's getCurrentThreadCpuTime() method returns the CPU time for the current thread. The getCurrentThreadUserTime() method returns the thread's user time. Both of these report times in nanoseconds

    如果应用程序是多线程的,则需要记录每个应用程序线程的cpu时间,并将其相加,以获得应用程序在所有线程中占用的总cpu时间

    话虽如此,如果你真的很想分析你的cpu消耗,你可能应该使用一个分析器。你可以从一个免费的开源软件开始,比如visualvm(也与jdk捆绑在一起),它将(除其他外)非常容易地回答这个确切的问题