我正在尝试用java创建基准测试.目前我有以下简单的方法:
public static long runTest(int times){
long start = System.nanoTime();
String str = "str";
for(int i=0; i<times; i++){
str = "str"+i;
}
return System.nanoTime()-start;
}
Run Code Online (Sandbox Code Playgroud)
我目前在另一个多次发生的循环中多次进行此循环,并获得运行此方法所需的最小/最大/平均时间.然后我在另一个线程上开始一些活动并再次测试.基本上我只想获得一致的结果......如果我有一千万次runTest循环,它似乎非常一致:
Number of times ran: 5
The max time was: 1231419504 (102.85% of the average)
The min time was: 1177508466 (98.35% of the average)
The average time was: 1197291937
The difference between the max and min is: 4.58%
Activated thread activity.
Number of times ran: 5
The max time was: 3872724739 (100.82% of the average)
The min time was: 3804827995 (99.05% of the average)
The average time was: 3841216849
The difference between the max and min is: 1.78%
Running with thread activity took 320.83% as much time as running without.
Run Code Online (Sandbox Code Playgroud)
但这似乎有点多,并且需要一些时间......如果我在runTest循环中尝试较低的数字(100000)...它开始变得非常不一致:
Number of times ran: 5
The max time was: 34726168 (143.01% of the average)
The min time was: 20889055 (86.02% of the average)
The average time was: 24283026
The difference between the max and min is: 66.24%
Activated thread activity.
Number of times ran: 5
The max time was: 143950627 (148.83% of the average)
The min time was: 64780554 (66.98% of the average)
The average time was: 96719589
The difference between the max and min is: 122.21%
Running with thread activity took 398.3% as much time as running without.
Run Code Online (Sandbox Code Playgroud)
有没有办法可以像这样做一个既稳定又高效/快速的基准?
顺便说一下,我没有测试开始和结束时间之间的代码.我正在以某种方式测试CPU负载(请参阅我如何开始一些线程活动并重新测试).所以我认为我正在寻找的东西替代我在"runTest"中的代码,它将产生更快,更一致的结果.
谢谢
简而言之:
(微)基准测试非常复杂,因此使用像Benchmarking框架http://www.ellipticgroup.com/misc/projectLibrary.zip这样的工具- 并且仍然对结果持怀疑态度("将微信任放在微观上 -基准",Cliff博士点击).
详细地:
有很多因素可以强烈影响结果:
Brent Boyer的文章"健壮的Java基准测试,第1部分:问题"(http://www.ibm.com/developerworks/java/library/j-benchmark1/index.html)很好地描述了所有这些问题以及是否/什么你可以对付它们(例如使用JVM选项或事先调用ProcessIdleTask).
您将无法消除所有这些因素,因此进行统计是一个好主意.但:
上面提到的Benchmark框架(http://www.ellipticgroup.com/misc/projectLibrary.zip)使用了这些技术.您可以在Brent Boyer的文章"Robust Java benchmarkinging,Part 2:Statistics and solutions"(https://www.ibm.com/developerworks/java/library/j-benchmark2/)中阅读它们.