度量JAVA中某部分代码所消耗的CPU时间



我目前正在尝试测量我的java代码的一部分实际消耗的cpu时间。我读到要获得CPU时间你必须使用

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

,但实际上,当我尝试在这段代码中测量它时,当经过的时间等于0 .....时抛出错误(在我看来,这在纳秒精度下是不可能的)。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);
                }

你知道吗?我没有正确使用CPUThread部分吗?我应该使用外部java基准吗?

Thanks in advance

我应该使用外部java基准吗?

是的,请这样做。Jprofiler在其他有用的指标中测量实际运行时间。

SystemRuntime类的方法将对您有所帮助。看一下:

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

例如:你可以使用:System.currentTimeMillis();,它以毫秒为单位返回程序之前和之后的时间!(main方法开头或结尾!)

最新更新