Skip to content

Instantly share code, notes, and snippets.

@mtkd
Created January 7, 2012 16:22
Show Gist options
  • Select an option

  • Save mtkd/1575178 to your computer and use it in GitHub Desktop.

Select an option

Save mtkd/1575178 to your computer and use it in GitHub Desktop.
IPaddr.new().to_i performance
require 'ipaddr'
require 'benchmark'
def iptoint1(ip)
IPAddr.new(ip, Socket::AF_INET).to_i
end
def iptoint2(ip)
if (ip.kind_of?(String) &&
ip =~ /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/)
ip = be_to_ui(Regexp.last_match().to_a.slice(1..4))
end
return ip
end
def be_to_ui(s)
i = 0
s.each { |b| i = ((i << 8) | (b.to_i & 0x0ff)) }
return i
end
def rand_ip
IPAddr.new(rand(2**32), Socket::AF_INET)
end
Benchmark.bm do |x|
x.report { 100000.times do; iptoint1(rand_ip); end; }
x.report { 100000.times do; iptoint2(rand_ip); end; }
end
# user system total real
# 0.280000 0.000000 0.280000 ( 0.287339)
# 0.170000 0.000000 0.170000 ( 0.169714)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment