Skip to content

Instantly share code, notes, and snippets.

@eiiches
Created May 9, 2013 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eiiches/5547843 to your computer and use it in GitHub Desktop.
Save eiiches/5547843 to your computer and use it in GitHub Desktop.
import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class Test {
private static final int N = 128 * 1024 * 1024;
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
{
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Unsafe unsafe = (Unsafe) theUnsafe.get(null);
long astart = System.nanoTime();
final long ptr = unsafe.allocateMemory(N);
long aend = System.nanoTime();
System.out.printf("Unsafe alloc took %10s nano seconds%n", aend - astart);
long wstart = System.nanoTime();
for (int i = 0; i < N; ++i) {
unsafe.putByte(ptr + i, (byte) 1);
}
long wend = System.nanoTime();
System.out.printf("Unsafe write took %10s nano seconds%n", wend - wstart);
long rstart = System.nanoTime();
int s = 0;
for (int i = 0; i < N; ++i) {
s += unsafe.getByte(ptr + i);
}
long rend = System.nanoTime();
System.out.printf("Unsafe read took %10s nano seconds%n", rend - rstart);
unsafe.freeMemory(ptr);
System.out.println(s);
}
{
long astart = System.nanoTime();
final byte[] array = new byte[N];
long aend = System.nanoTime();
System.out.printf("Array alloc took %10s nano seconds%n", aend - astart);
long wstart = System.nanoTime();
for (int i = 0; i < N; ++i) {
array[i] = (byte) 1;
}
long wend = System.nanoTime();
System.out.printf("Array write took %10s nano seconds%n", wend - wstart);
long rstart = System.nanoTime();
int s = 0;
for (int i = 0; i < N; ++i) {
s += array[i];
}
long rend = System.nanoTime();
System.out.printf("Array read took %10s nano seconds%n", rend - rstart);
System.out.println(s);
}
// Unsafe alloc took 16142 nano seconds
// Unsafe write took 120145208 nano seconds
// Unsafe read took 114300970 nano seconds
// 134217728
// Array alloc took 42636826 nano seconds
// Array write took 20694570 nano seconds
// Array read took 63825587 nano seconds
// 134217728
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment