性能测试 java,Java性能测试

I want to do some timing tests on a Java application. This is what I am currently doing:

long startTime = System.currentTimeMillis();

doSomething();

long finishTime = System.currentTimeMillis();

System.out.println("That took: " + (finishTime - startTime) + " ms");

Is there anything "wrong" with performance testing like this? What is a better way?

解决方案

The one flaw in that approach is that the "real" time doSomething() takes to execute can vary wildly depending on what other programs are running on the system and what its load is. This makes the performance measurement somewhat imprecise.

One more accurate way of tracking the time it takes to execute code, assuming the code is single-threaded, is to look at the CPU time consumed by the thread during the call. You can do this with the JMX classes; in particular, with ThreadMXBean. You can retrieve an instance of ThreadMXBean from java.lang.management.ManagementFactory, and, if your platform supports it (most do), use the getCurrentThreadCpuTime method in place of System.currentTimeMillis to do a similar test. Bear in mind that getCurrentThreadCpuTime reports time in nanoseconds, not milliseconds.

Here's a sample (Scala) method that could be used to perform a measurement:

def measureCpuTime(f: => Unit): java.time.Duration = {

import java.lang.management.ManagementFactory.getThreadMXBean

if (!getThreadMXBean.isThreadCpuTimeSupported)

throw new UnsupportedOperationException(

"JVM does not support measuring thread CPU-time")

var finalCpuTime: Option[Long] = None

val thread = new Thread {

override def run(): Unit = {

f

finalCpuTime = Some(getThreadMXBean.getThreadCpuTime(

Thread.currentThread.getId))

}

}

thread.start()

while (finalCpuTime.isEmpty && thread.isAlive) {

Thread.sleep(100)

}

java.time.Duration.ofNanos(finalCpuTime.getOrElse {

throw new Exception("Operation never returned, and the thread is dead " +

"(perhaps an unhandled exception occurred)")

})

}

(Feel free to translate the above to Java!)

This strategy isn't perfect, but it's less subject to variations in system load.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值