Skip to content

Instantly share code, notes, and snippets.

@stepancheg
Created November 18, 2009 00:12
Show Gist options
  • Save stepancheg/237408 to your computer and use it in GitHub Desktop.
Save stepancheg/237408 to your computer and use it in GitHub Desktop.
import java.io._
import java.nio._
val f = new File("/dev/zero")
val size = 10000
val count = 100000
def readUsingInputStream() {
val is = new FileInputStream(f)
val b = new Array[Byte](size)
for (i <- 1 to count) {
val c = is.read(b)
if (c != size)
throw new Exception()
}
is.close()
}
def readUsingByteChannel() {
val is = new FileInputStream(f)
val c = is.getChannel
val b = ByteBuffer.allocateDirect(size)
for (i <- 1 to count) {
c.read(b)
if (b.position != size)
throw new Exception()
b.rewind()
}
is.close()
}
def profile(what: String)(action: => Unit) = {
val start = System.currentTimeMillis()
action
val delta = System.currentTimeMillis() - start
println(what + ": " + delta)
}
while (true) {
profile("readUsingByteChannel")(readUsingByteChannel())
profile("readUsingInputStream")(readUsingInputStream())
}
println("$")
// vim: set ts=4 sw=4 et:
/*
outputs:
readUsingByteChannel: 132
readUsingInputStream: 254
readUsingByteChannel: 144
readUsingInputStream: 253
readUsingByteChannel: 133
readUsingInputStream: 251
readUsingByteChannel: 133
readUsingInputStream: 251
readUsingByteChannel: 132
readUsingInputStream: 300
readUsingByteChannel: 132
readUsingInputStream: 254
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment