How to use Ruby Benchmark

Maybe you are new to the Ruby ecosystem, and you might saw fancy benchmarks for present? vs exists? or things like that.

If you wanted to figure how to use Benchmark, how they did it?:

The Benchmark module provides methods for measuring and reporting the time used to execute Ruby code.

Easy steps:

$ irb

Try to type Benchmark

irb(main):001:0> Benchmark  
NameError: uninitialized constant Benchmark  
    from (irb):1
    from /Users/zazvick/.rbenv/versions/2.3.1/bin/irb:11:in `<main>'

So, you need to require this module.

irb(main):002:0> require 'benchmark'  
=> true

After that you can start running your benchmark as this example:

# Benchmark experiment No1

def hashit1  
 {a: "hola", b: "como", c: "estas"}

def hashit2  
 {a: "hola", b: "como", c: "estas"}.freeze

def hashit3  
 {a: "hola".freeze, b: "como".freeze, c: "estas".freeze}

Benchmark.bmbm do |x|"normal") { hashit1 }"frozen") { hashit2 }"frozen2") { hashit3 }


Rehearsal -------------------------------------------  
normal    0.000000   0.000000   0.000000 (  0.000007)  
frozen    0.000000   0.000000   0.000000 (  0.000007)  
frozen2   0.000000   0.000000   0.000000 (  0.000005)  
---------------------------------- total: 0.000000sec

              user     system      total        real
normal    0.000000   0.000000   0.000000 (  0.000004)  
frozen    0.000000   0.000000   0.000000 (  0.000003)  
frozen2   0.000000   0.000000   0.000000 (  0.000003)

=> [#<Benchmark::Tms:0x007fc944027de8 @label="normal", @real=3.6910059861838818e-06, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.0, @total=0.0>, #<Benchmark::Tms:0x007fc944027dc0 @label="frozen", @real=3.3570104278624058e-06, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.0, @total=0.0>, #<Benchmark::Tms:0x007fc944027d70 @label="frozen2", @real=2.7450150810182095e-06, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.0, @total=0.0>]

Pretty naive, isn't?

That's all folks, see you in the next post, follow me on @zazvick

Victor Velazquez

Coder, Musician, Startups, Passionate Dancer & Life Lover. Software Engineer at MagmaLabs, Co-founder of Web Dev Talks, Co-founder of Voltaire, Co-founder of Paqkit, Ex-co-founder of Zaznova.

Subscribe to The zazvick's blog

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!