gpt4 book ai didi

java - 记录程序的CPU时间

转载 作者:行者123 更新时间:2023-12-02 07:17:17 29 4
gpt4 key购买 nike

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

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

这种方法的问题是,如果有多个程序在运行,那么 endTime 和 starttime 之间的差值并不是我的程序所花费的时间。这也是在CPU等中调度不同程序所花费的时间。但是,我只想记录我的程序所花费的时间。我如何获得这个时间?

最佳答案

你可以在这个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 捆绑在一起)它将(以及其他许多事情)非常轻松地回答这个确切的问题。

关于java - 记录程序的CPU时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14788976/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com