记录程序的 CPU 时间 [英] Recording Program's CPU Time

查看:75
本文介绍了记录程序的 CPU 时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to record the time taken by my Java program. Most forums suggest something like:

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

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

The problem with this approach is that if there are multiple programs running, then the difference between endTime and starttime is not the time taken by my program. It is also the time taken during scheduling of different programs in the CPU etc. However, I am only interested to record the time taken by my program. How do I get this time?

推荐答案

你可以在这个文章.引用文章:

you can find the answer in this article. to quote from the article:

呼叫管理工厂 .getThreadMXBean() 获取一个 ThreadMXBean描述当前的 JVM 线程.bean 的 getCurrentThreadCpuTime()方法返回当前线程的 CPU 时间.这getCurrentThreadUserTime() 方法返回线程的用户时间.两个都这些报告时间以纳秒为单位

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 时间.

if your application is multi-threaded you'd need to record the cpu time per application thread and sum them up to get the total cpu time taken up by your application across all of its threads.

话虽如此 - 如果您真的很认真地分析您的 CPU 消耗,您可能应该使用分析器.你可以从一个免费的开源软件开始,比如 visualvm(也与 jdk 捆绑在一起),它将(在许多其他事情)很容易回答这个确切的问题.

having said that - if youre really serious about profiling your cpu consumption you should probably be using a profiler. you can start with a free open source one like visualvm (also comes bundled with the jdk) which will (among many other things) answer this exact question very easily.

这篇关于记录程序的 CPU 时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆