首页 > 代码库 > nanoTime对volatile 测试的一种写法

nanoTime对volatile 测试的一种写法

今天脑筋有点搭牢,想了半天才看出为什么以下两段代码效果是相同的。。。

第一种好处是可以直接批量复制黏贴system.out,  不用改什么东西

  private static long i;
  private volatile static long vt;
  private static final int TEST_SIZE = 10000000;

?
1
2
3
4
5
6
7
long time = System.nanoTime();
for (int n = 0; n < TEST_SIZE; n++)
    vt = System.currentTimeMillis();
System.out.println(-time + (time = System.nanoTime()));<br>
for (int n = 0; n < TEST_SIZE; n++)
    i = System.currentTimeMillis();
System.out.println(-time + (time = System.nanoTime()));

  

这种每次要在循环头上重置nanoTime

?
1
2
3
4
5
6
7
8
9
10
11
<span>private static long i;</span><br><span>private volatile static long vt;</span><br><span>private static final int TEST_SIZE = 10000000;</span><br><br>long time = System.nanoTime();
for (int n = 0; n < TEST_SIZE; n++) {
            vt = System.currentTimeMillis();
}
System.out.println((System.nanoTime() - time));
 
time = System.nanoTime();
for (int n = 0; n < TEST_SIZE; n++) {
      i = System.currentTimeMillis();
}
System.out.println((System.nanoTime() - time));