0

I want to make a test, what is more efficient write to a regular variable or write to volatile variable. I wrote this code for the test

private int v1= 42;
private volatile int v2 = 43;

public void measure(){
   long startRegular = System.nanoTime();
   v1++;
   long endRegular= System.nanoTime();
   v2++;
   long endVoltaile = System.nanoTime();
   long rt = endRegular - startRegular;
   long vt = endVoltaile - endRegular;
   System.out.println("regular time : " + rt + " voltaile time " + vt);
}

The output from this program is diffrenet result for every run. Is this a valid test? or there is a better way to test it?

Ron Badur
  • 1,873
  • 2
  • 15
  • 34
  • Your test has many flaws - try to use [jmh](http://openjdk.java.net/projects/code-tools/jmh/). – assylias May 03 '17 at 12:27
  • See for example: http://hg.openjdk.java.net/code-tools/jmh/file/cdac7ecd1392/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_03_States.java – assylias May 03 '17 at 12:28
  • Your test is completely broken as you're measuring how long `System.nanoTime()` takes (it's much slower than the increment). And there are more reasons. – maaartinus May 03 '17 at 12:28

0 Answers0