Skip to content

Instantly share code, notes, and snippets.

Created April 20, 2013 08:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/5425245 to your computer and use it in GitHub Desktop.
Save anonymous/5425245 to your computer and use it in GitHub Desktop.
set vs check then set for volatile (and non) in java
package misc.bench;
import java.util.Random;
import java.util.concurrent.atomic.AtomicIntegerArray;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.collect.ObjectArrays;
public class CondWriteBench extends SimpleBenchmark {
private static final int ARRAY_LENGTH = 1000;
private final int source[] = new int[ARRAY_LENGTH];
private final int targetContents[] = new int[ARRAY_LENGTH];
enum ArrayType { SAME, DIFFERENT };
@Param ArrayType arrayType;
@Override
protected void setUp() throws Exception {
Random r = new Random();
for (int i=0; i < ARRAY_LENGTH; i++) {
source[i] = r.nextInt() & ~1;
targetContents[i] = arrayType == ArrayType.SAME ? source[i] : (r.nextInt() | 1);
}
}
public int timeCopyNoCheck(int reps) {
int[] target = new int[ARRAY_LENGTH];
while (reps-- > 0) {
System.arraycopy(this.targetContents, 0, target, 0, ARRAY_LENGTH);
for (int i=0; i < ARRAY_LENGTH; i++) {
target[i] = source[i];
}
}
return target[new Random().nextInt(ARRAY_LENGTH)];
}
public int timeCopyCheck(int reps) {
int[] target = new int[ARRAY_LENGTH];
while (reps-- > 0) {
System.arraycopy(this.targetContents, 0, target, 0, ARRAY_LENGTH);
for (int i=0; i < ARRAY_LENGTH; i++) {
int x = source[i];
if (target[i] != x) {
target[i] = x;
}
}
}
return target[new Random().nextInt(ARRAY_LENGTH)];
}
public int timeCopyNoCheckAI(int reps) {
int total = 0, rindex = new Random().nextInt(ARRAY_LENGTH);
AtomicIntegerArray target = new AtomicIntegerArray(ARRAY_LENGTH);
while (reps-- > 0) {
if (arrayType == ArrayType.DIFFERENT) {
copyToAI(targetContents, target);
}
for (int i=0; i < ARRAY_LENGTH; i++) {
target.set(i, source[i]);
}
total += target.get(rindex);
}
return total;
}
public int timeCopyCheckAI(int reps) {
int total = 0, rindex = new Random().nextInt(ARRAY_LENGTH);
AtomicIntegerArray target = new AtomicIntegerArray(ARRAY_LENGTH);
while (reps-- > 0) {
if (arrayType == ArrayType.DIFFERENT) {
copyToAI(targetContents, target);
}
for (int i=0; i < ARRAY_LENGTH; i++) {
int x = source[i];
if (target.get(i) != x) {
target.set(i, x);
}
}
total += target.get(rindex);
}
return total;
}
private static void copyToAI(int[] source, AtomicIntegerArray target) {
assert source.length == target.length();
for (int i=0; i<source.length; i++) {
target.lazySet(i, source[i]);
}
}
public static void main(String[] args) {
Runner.main(CondWriteBench.class, args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment