简体   繁体   English

测量JAVA中一部分代码所花费的CPU时间

[英]Measure the CPU time elapsed for a part of code in JAVA

I'm currently trying to measure the real elapsed cpu time for a part of my code in java. 我目前正在尝试测量Java中部分代码的实际经过的CPU时间。 I read that to get the CPU time you have to use the 我读到要获得CPU时间,您必须使用

cpuTime = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();

but in fact when I try to measure it in that piece of code, an error is thrown when the elapsed time is equal to zero..... (which it appears to me to be impossible with a nano-sec precision). 但是实际上,当我尝试在那段代码中对其进行度量时,如果经过时间等于零,则会引发错误.....(在我看来,以纳秒的精度是不可能的)。 The while loop can be big or can also very small (aout 10 instuctions min). while循环可以很大,也可以很小(至少10次指示)。

long startTime = ManagementFactory.getThreadMXBean()
                        .getCurrentThreadCpuTime();
// reset with seed solution for each neighborRule and
// each pivoting rule
t.setCurrentBestSolution(seedSolution);
while (t.chooseNextImprovingNeighborSolution(pivotingRule,
                        neighborRule));                 
long endTime = ManagementFactory.getThreadMXBean()
                    .getCurrentThreadCpuTime();
if (endTime - startTime == 0) {
    System.err.println(pivotingRule + ":" + neighborRule);
    System.err.println("END TIME:" + endTime);
    System.err.println("START TIME:" + startTime);
                }

Any idea ? 任何想法 ? Am I not using properly the CPUThread part ? 我没有正确使用CPUThread部分吗? Should I use an external java benchmarker ? 我应该使用外部Java基准测试程序吗?

Thanks in advance 提前致谢

Should I use an external java benchmarker ? 我应该使用外部Java基准测试程序吗?

Yes please do. 是的,请这样做。 Jprofiler measures the real elapsed time among other useful metrics. Jprofiler在其他有用的指标中测量实际经过的时间。

The methods of System and Runtime class will help you. SystemRuntime类的方法将为您提供帮助。 Take a look on: 看一下:

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Runtime.html http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html http://docs.oracle.com/javase/1.5.0/docs/api/java/lang /Runtime.html

For example: You can use: System.currentTimeMillis(); 例如:您可以使用: System.currentTimeMillis(); which returns the time in millisecond, before and after your program! 它以毫秒为单位返回程序前后的时间! (at the beginning or end of main method!) (在main方法的开头或结尾!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM