Skip to content

Instantly share code, notes, and snippets.

@headius
Created November 24, 2010 21:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save headius/714418 to your computer and use it in GitHub Desktop.
Save headius/714418 to your computer and use it in GitHub Desktop.
~/projects/jruby ➔ jruby memory_mapped.rb
Reading and writing memory-mapped
2.355000 0.000000 2.355000 ( 2.299000)
1.943000 0.000000 1.943000 ( 1.942000)
2.014000 0.000000 2.014000 ( 2.014000)
1.899000 0.000000 1.899000 ( 1.899000)
1.870000 0.000000 1.870000 ( 1.870000)
Reading from disk
2.982000 0.000000 2.982000 ( 2.982000)
3.031000 0.000000 3.031000 ( 3.031000)
3.027000 0.000000 3.027000 ( 3.027000)
3.404000 0.000000 3.404000 ( 3.405000)
3.775000 0.000000 3.775000 ( 3.775000)
require 'java'
require 'benchmark'
require 'fileutils'
java_import java.nio.channels.FileChannel
# copy jruby.jar to a tmp location
FileUtils.cp 'lib/jruby.jar', '/tmp/jruby.jar'
tmp_file = File.open('/tmp/jruby.jar', 'r+')
# get the channel and memory map
channel = tmp_file.to_channel
map = channel.map FileChannel::MapMode::READ_WRITE, 0, channel.size
map.load # load into memory
# perform many reads and writes
puts "Reading and writing memory-mapped"
5.times {
puts Benchmark.measure {
100.times {
bytes = Java::byte[channel.size].new
map.position 0
map.get bytes
map.position 0
map.put bytes
}
}
}
puts "Reading and writing disk"
5.times {
puts Benchmark.measure {
100.times {
tmp_file.seek 0
str = tmp_file.read
tmp_file.seek 0
tmp_file.write str
}
}
}
@hectcastro
Copy link

If I'm trying to randomly access portions of a large file (2-10GB) with JRuby, would there be a big incentive to leverage a method like this over the standard Ruby IO library? Isn't that using NIO under the covers?

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