我正在尝试使用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;
}
我目前在另一个循环中多次运行此循环,该循环发生多次,并获得运行此方法所需的最小/最大/平均时间。然后我在另一个线程上启动一些活动并再次进行测试。基本上,我只想获得一致的结果...如果我运行runTest循环1000万次,结果似乎相当一致:
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.
但是这似乎有点过分,需要花费一些时间... 如果我在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.
有没有一种方法可以进行如此一致且高效/快速的基准测试?
顺便说一下,我并不是在测试开始和结束时间之间的代码。我正在以某种方式测试CPU负载(看看我如何启动一些线程活动并重新测试)。因此,我认为我正在寻找的是一种替代我在“runTest”中拥有的代码的东西,它将产生更快和更一致的结果。
谢谢