Java 在开始测量性能之前,预热代码

Java 在开始测量性能之前,预热代码,java,sql,database,multithreading,performance-testing,Java,Sql,Database,Multithreading,Performance Testing,我已经开始从事一个项目,在该项目中,我将传递需要使用的线程数,然后我将尝试测量执行SELECT sql所需的时间,以便在此行preparedStatement.executeQuery()之前有一个计数器和一个计数器,用于测量此行之后的时间 下面是我的代码片段- public class TestPool { public static void main(String[] args) { final int no_of_threads = 10;

我已经开始从事一个项目,在该项目中,我将传递需要使用的线程数,然后我将尝试测量执行
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);
    }
}
公共类测试池{
公共静态void main(字符串[]args){
最终内螺纹数=10;
//创建具有给定大小的线程池
ExecutorService=Executors.newFixedThreadPool(没有\u个线程);
//将一些任务排队
对于(int i=0;i<3*没有线程;i++){
提交(新线程任务());
}
//等待终止
service.shutdown();
服务。等待终止(Long.MAX_值,时间单位:天);
//现在在这里打印选择直方图
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();
        }

        ..............

    }
}
class ThreadTask实现可运行{
private PreparedStatement PreparedStatement=null;
私有结果集rs=null;
公共静态ConcurrentHashMap selectHistogram=新ConcurrentHashMap();
公共线程任务(){
}
@凌驾
公开募捐{
...........
长启动=System.nanoTime();
rs=preparedStatement.executeQuery();
long end=System.nanoTime()-开始;
final AtomicLong before=选择直方图。putIfAbsent(结束/100000L,新的AtomicLong(1L));
如果(在!=null之前){
before.incrementAndGet();
}
..............
}
}
问题陈述:-


今天我开了一个设计会议,大多数人都说不要在运行程序的时候就开始测量时间。进行一些预热,然后开始测量。所以我想在那之后,这样做是有道理的。现在我在想,我应该如何在我的代码中加入这些变化。我这样做的依据是什么?有人能提出一些建议吗?

最简单的预热方法之一是,在运行实际(定时)测试之前,在同一JVM中运行相同的测试,而无需计时。您应该运行数千次迭代,以使JIT有机会识别和优化热点。答案中有更多的细节(关于这一点以及您需要考虑的其他事项)

您可以运行它大约15分钟来创建新的线程任务。然后清除selectHistogram,并使用所需的线程数重新运行以打印度量。

您是否正在尝试度量SQL的性能?为什么不在数据库端测量它,因为它消除了应用程序端的所有不确定性。