Skip to content

Instantly share code, notes, and snippets.

@toruw
Created March 29, 2015 14:21
Show Gist options
  • Save toruw/85d3911a842b1d423073 to your computer and use it in GitHub Desktop.
Save toruw/85d3911a842b1d423073 to your computer and use it in GitHub Desktop.
IO performance comparison in java
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel.MapMode;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class IOPerfTest {
private RandomAccessFile db;
@Before
public void setUp() throws Exception {
db = new RandomAccessFile("test.dat", "r");
}
@After
public void tearDown() throws Exception {
db.close();
}
@Test
public void testIO() throws Exception {
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
db.read();
}
long end = System.currentTimeMillis();
System.out.println("Test IO::" + (end - start) + " ms");
}
@Test
public void testIOAll() throws Exception {
byte[] buff = new byte[1000000];
long start = System.currentTimeMillis();
db.read(buff);
long end = System.currentTimeMillis();
System.out.println("Test IOAll::" + (end - start) + " ms");
}
@Test
public void testNIO() throws Exception {
ByteBuffer buff = db.getChannel().map(MapMode.READ_ONLY, 0, db.length());
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
buff.get();
}
long end = System.currentTimeMillis();
System.out.println("Test NIO::" + (end - start) + " ms");
}
@Test
public void testNIOAll() throws Exception {
byte[] _buff = new byte[1000000];
ByteBuffer buff = db.getChannel().map(MapMode.READ_ONLY, 0, db.length());
long start = System.currentTimeMillis();
buff.get(_buff);
long end = System.currentTimeMillis();
System.out.println("Test NIOAll::" + (end - start) + " ms");
}
}
@toruw
Copy link
Author

toruw commented Mar 29, 2015

Result

Test IO::730 ms
Test IOAll::3 ms
Test NIO::8 ms
Test NIOAll::0 ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment