如何在Java中使用嵌套的for循环正确计时?

时间:2019-07-14 01:06:45

标签: java eclipse benchmarking

我正在尝试计时一个客户端从另一个客户端接收一些消息所花费的时间。当创建一个for循环并计时结果时,它给了我一个正常的结果:

 // 1 trial sending 10 messages
    startTime = System.nanoTime();
    for (int j = 0; j < 10; j++) {  
        receivedMessage = receivingQueue.receive(MESSAGEWAITTIME,TimeUnit.SECONDS).get(); // receives incoming messages as Mqtt5Publish instances  (.get() will return the Mqtt5Publish without the Optional<>)                                                                     
        byte[] tempData = receivedMessage.getPayloadAsBytes();    // converts the Optional<Mqtt5Publish> to a byte array 
        String getData = new String(tempData);  // converts the byte array to a String 
        out.println(getData);  // writes each message as a String to a text file
    }
        out.close();

    endTime = System.nanoTime();

上面的代码给了我平均191毫秒的时间(我稍后在代码中将其从nano转换),而当我添加一个嵌套的for循环时,我的结果实际上更少了,并且在下面的代码中下降到了35毫秒左右。我知道JIT,但已在Eclipse的JV参数中使用以下命令将其关闭:-Djava.compiler=NONE,但代码看起来仍然像是由编译器优化的。

// 50 trials sending 10 messages
     for (int i = 0; i < 50; i++) {
            startTime = System.nanoTime();

            for (int j = 0; j < 10; j++) {  
                receivedMessage = receivingQueue.receive(MESSAGEWAITTIME,TimeUnit.SECONDS).get(); // receives incoming messages as Mqtt5Publish instances  (.get() will return the Mqtt5Publish without the Optional<>)                                                                     
                byte[] tempData = receivedMessage.getPayloadAsBytes();    // converts the Optional<Mqtt5Publish> to a byte array 
                String getData = new String(tempData);  // converts the byte array to a String 
                out.println(getData);  // writes each message as a String to a text file
            }
                out.close();

            endTime = System.nanoTime();
            timeReceive = endTime - startTime; 
            timeReceiveTotal = timeReceive + timeReceiveTotal;
        }
            timeReceiveTotal = timeReceiveTotal/50;  // gets the average of 50 trials
    }

0 个答案:

没有答案