测量时间间隔和乱序执行 [英] Measuring time interval and out of order execution
问题描述
我一直在阅读有关Java内存模型的内容,我知道编译器可以重新组织语句以优化代码。
I've been reading about Java memory model and I'm aware that it's possible for compiler to reorganize statements to optimize code.
假设我有以下内容代码:
Suppose I had a the following code:
long tick = System.nanoTime();
function_or_block_whose_time_i_intend_to_measure();
long tock = System.nanoTime();
编译器是否会重新组织代码,以便在tick之间不执行我想要测量的内容和tock?例如,
would the compiler ever reorganize the code in a way that what I intend to measure is not executed between tick and tock? For example,
long tick = System.nanoTime();
long tock = System.nanoTime();
function_or_block_whose_time_i_intend_to_measure();
如果是这样,保留执行订单的正确方法是什么?
If so, what's the right way to preserve execution order?
编辑:
说明使用nanoTime执行无序执行的示例:
Example illustrating out-of-order execution with nanoTime :
public class Foo {
public static void main(String[] args) {
while (true) {
long x = 0;
long tick = System.nanoTime();
for (int i = 0; i < 10000; i++) { // This for block takes ~15sec on my machine
for (int j = 0; j < 600000; j++) {
x = x + x * x;
}
}
long tock = System.nanoTime();
System.out.println("time=" + (tock - tick));
x = 0;
}
}
}
上述代码的输出:
time=3185600
time=16176066510
time=16072426522
time=16297989268
time=16063363358
time=16101897865
time=16133391254
time=16170513289
time=16249963612
time=16263027561
time=16239506975
在上面的示例中,第一次迭代中测量的时间明显低于后续运行中的测量时间。我以为这是由于乱序执行造成的。第一次迭代我做错了什么?
In the above example, the time measured in first iteration is significantly lower than the measured time in the subsequent runs. I thought this was due to out of order execution. What am I doing wrong with the first iteration?
推荐答案
Java内存模型(JMM)定义了一个名为<$ c $的部分排序c>在之前发生在程序的所有操作上。定义了七个规则以确保在
订购之前发生。其中一个名为程序订单规则
:
Java Memory Model (JMM) defines a partial ordering called happens-before
on all actions with the program. There are seven rules defined to ensure happens-before
ordering. One of them is called Program order rule
:
程序订单规则。线程中的每个动作都发生在该程序中稍后出现的该线程中的每个动作之前。
Program order rule. Each action in a thread happens-before every action in that thread that comes later in the program order.
根据此规则,您的编译器不会重新排序代码。
According to this rule, your code will not be re-ordered by the compiler.
这本书 Java Concurrency in Practice 对此主题给出了很好的解释。
The book Java Concurrency in Practice gives an excellent explanation on this topic.
这篇关于测量时间间隔和乱序执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!