-
-
Save jnorthrup/8b2ae89ef6df5ea6120c4c75153e11db to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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