Skip to content

Instantly share code, notes, and snippets.

@rwz
Created January 3, 2014 20:49

Revisions

  1. rwz created this gist Jan 3, 2014.
    44 changes: 44 additions & 0 deletions bm.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    require "benchmark/ips"
    require "set"

    OLD_CODE = ->(n){
    mod10 = n % 10
    mod100 = n % 100

    if mod10 == 1 && mod100 != 11
    :one
    elsif [2, 3, 4].include?(mod10) && ![12, 13, 14].include?(mod100)
    :few
    elsif mod10 == 0 || (5..9).to_a.include?(mod10) || (11..14).to_a.include?(mod100)
    :many
    else
    :other
    end
    }

    FROM_2_TO_4 = (2..4).to_set
    FROM_5_TO_9 = (5..9).to_set
    FROM_11_TO_14 = (11..14).to_set
    FROM_12_TO_14 = (12..14).to_set

    NEW_CODE = ->(n){
    mod10 = n % 10
    mod100 = n % 100

    if mod10 == 1 && mod100 != 11
    :one
    elsif FROM_2_TO_4.include?(mod10) && !FROM_12_TO_14.include?(mod100)
    :few
    elsif mod10 == 0 || FROM_5_TO_9.include?(mod10) || FROM_11_TO_14.include?(mod100)
    :many
    else
    :other
    end
    }

    SAMPLE = 1000.times.map{ rand(0...999) } + 100.times.map{ rand(0...999).to_f / 10 }

    Benchmark.ips do |x|
    x.report("old code"){ SAMPLE.each{ |n| OLD_CODE[n] }}
    x.report("new code"){ SAMPLE.each{ |n| NEW_CODE[n] }}
    end