Skip to content

Instantly share code, notes, and snippets.

@komamitsu
Created November 28, 2014 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komamitsu/da269fa7d494e543e6bf to your computer and use it in GitHub Desktop.
Save komamitsu/da269fa7d494e543e6bf to your computer and use it in GitHub Desktop.
require 'redis'
class RedisBench
def initialize(count)
@count = count
@r = Redis.new
end
def bench(prepare_items, label, &blk)
@r.flushall
if prepare_items
@count.times do |i|
@r.set(sprintf('k%07d', i), sprintf('va%07d', i))
end
end
s = Time.now
blk.call
puts "#{label}: #{Time.now - s} sec"
end
private :bench
def run
[true, false].each do |prepare_items|
if prepare_items
puts "=========== with prepared items ==========="
else
puts "=========== with no items ==========="
end
puts
bench(prepare_items, 'set') do
@count.times do |i|
@r.set(sprintf('k%07d', i), sprintf('va%07d', i))
end
end
bench(prepare_items, 'getset') do
@count.times do |i|
@r.getset(sprintf('k%07d', i), sprintf('vb%07d', i))
end
end
bench(prepare_items, 'eval(cas)') do
lua_script = <<-EOF
local old_v = redis.call('get', KEYS[1])
if (old_v == false) then
redis.call('set', KEYS[1], ARGV[1])
end
return old_v
EOF
@count.times do |i|
@r.eval(lua_script, [sprintf('k%07d', i)], [sprintf('vc%07d', i)])
end
end
bench(prepare_items, 'eval(multi-cas)') do
xs = []
@count.times do |i|
xs << [sprintf('k%07d', i), sprintf('vd%07d', i)]
if xs.size == 20
lua_script = <<-EOF
local old_vs = redis.call('mget', #{xs.size.times.map{|i| "KEYS[#{i + 1}]"}.join(',')})
local len = #{xs.size}
local i = 1
while i <= len do
if (old_vs[i] == false) then
redis.call('set', KEYS[i], ARGV[i])
end
i = i + 1
end
return old_vs
EOF
@r.eval(lua_script, xs.map{|kv| kv[0]}, xs.map{|kv| kv[1]})
xs.clear
end
end
end
puts
end
end
end
RedisBench.new(10000).run
@komamitsu
Copy link
Author

=========== with prepared items ===========

set: 0.873195 sec
getset: 0.907826 sec
eval(cas): 1.095413 sec
eval(multi-cas): 0.198834 sec

=========== with no items ===========

set: 0.935378 sec
getset: 0.882512 sec
eval(cas): 1.101836 sec
eval(multi-cas): 0.201168 sec

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