java在开始测量性能之前对代码进行预热
我已经开始在一个项目中工作,在这个项目中,我将传递需要使用的线程数量,然后我将尝试测量执行SELECT sql
所花费的时间,因此我在这一行preparedStatement.executeQuery();
之前有一个计数器,在这一行之后有一个计数器来测量时间
下面是我的代码片段-
public class TestPool {
public static void main(String[] args) {
final int no_of_threads = 10;
// create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(no_of_threads);
// queue some tasks
for(int i = 0; i < 3 * no_of_threads; i++) {
service.submit(new ThreadTask());
}
// wait for termination
service.shutdown();
service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
// Now print the select histogram here
System.out.println(ThreadTask.selectHistogram);
}
}
下面是实现Runnable接口的ThreadTask类-
class ThreadTask implements Runnable {
private PreparedStatement preparedStatement = null;
private ResultSet rs = null;
public static ConcurrentHashMap<Long, AtomicLong> selectHistogram = new ConcurrentHashMap<Long, AtomicLong>();
public ThreadTask() {
}
@Override
public void run() {
...........
long start = System.nanoTime();
rs = preparedStatement.executeQuery();
long end = System.nanoTime() - start;
final AtomicLong before = selectHistogram.putIfAbsent(end / 1000000L, new AtomicLong(1L));
if (before != null) {
before.incrementAndGet();
}
..............
}
}
问题陈述:-
今天我开了一个设计会议,大多数人都说不要在运行程序的时候就开始测量时间。进行一些预热,然后开始测量。所以我想在那之后,这样做是有道理的。现在我在想,我应该如何在我的代码中加入这些变化。我这样做的依据是什么?有人能提出一些建议吗
# 1 楼答案
您可以运行它大约15分钟来创建新的线程任务。然后清除selectHistogram,并使用所需数量的线程重新运行以打印度量
# 2 楼答案
预热的最简单方法之一是在运行实际(定时)测试之前,在同一JVM中运行相同的测试,而无需计时。您应该运行数千次迭代,以使JIT有机会识别和优化热点。对How do I write a correct micro-benchmark in Java?的回答中有更多的细节(关于这一点和其他需要考虑的问题)