Java程序延迟问题

Java程序延迟问题,java,logging,log4j,execution,latency,Java,Logging,Log4j,Execution,Latency,我通过使用log4j和简单的文件读写创建日志来比较Java程序延迟 String content = "Writing"; File file = new File("D://filename.txt"); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } FileWriter fw = new Fil

我通过使用log4j和简单的文件读写创建日志来比较Java程序延迟

     String content = "Writing";

    File file = new File("D://filename.txt");

    // if file doesnt exists, then create it
    if (!file.exists()) {
        file.createNewFile();
    }

    FileWriter fw = new FileWriter(file);
    BufferedWriter bw = new BufferedWriter(fw);


    long startTimeF=System.nanoTime();
    for(int i=0;i<10;i++)   
    {
        bw.write(content);

    }
    bw.close();
    long endTimeF=System.nanoTime();
    System.out.println("Time elapsed for file write:"+(endTimeF-startTimeF));
    long startTimeL=System.nanoTime();
    for(int i=0;i<10;i++)   
    {
        _logger.info("Writing..:"+strDate); }
    long endTimeL=System.nanoTime();

    System.out.println("Time elapsed for logger    ="+(endTimeL-startTimeL));

如果希望对JVM中不同操作的速度进行基准测试,不要只运行一次,因为JVM在初始启动期间执行的各种额外耗时任务可能会影响结果。在循环中运行代码,然后平均每个操作的时间。如果在切换两种日志记录方法的位置之间仍然存在差异,那么说明这一点。您应该使用一些可接受的工作量来执行基准测试。如果一个代码块需要3或4毫秒,您不应该认真考虑。问题是,为什么我的log4j记录器在写入文件代码后执行时会显示很大的延迟时间,这意味着JVM需要一些时间来初始化。当您运行的基准测试太短时,结果将不准确。在这个场景中,Log4j也需要一些时间来初始化自己。它的记录器在运行时动态加载。如果您编写了一个更大的基准测试,因此初始化时间与正在测量的任务相比很短,那么在写入文件时,我希望有类似的性能
    for(int i=0;i<10;i++)   
    {
        _logger.info("writing..:"+strDate); }
    long endTimeL=System.nanoTime();

    System.out.println("Time elapsed for logger    ="+(endTimeL-startTimeL));

    long startTimeF=System.nanoTime();
    for(int i=0;i<10;i++)   
    {
        bw.write(content);

    }
    bw.close();
    long endTimeF=System.nanoTime();
    System.out.println("Time elapsed for file write:"+(endTimeF-startTimeF));
 What cause to get different output by only inter changing lines....(using Asynchronous Logging) ?