Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby equivalent to Ipython %timeit

Tags:

ruby

timing

tl;dr; How can I time how long something takes in Ruby?

Ipython's %timeit and %%timeit are two of my most frequently used IPython Magic commands (A Python Interactive shell) . Generically %timeit is not that different from a function like this:

def timeit(f, *args, **kwargs): 
  num_trials = estimate_number_of_trials_for_f(f, args, kwargs) 
  start = time.time() 
  for i in range(num_trials): 
    f(args, kwargs) 
  return time.time() - start

The advantage is that interactively it's possible to do something like this (not a great example use case I know):

In [119]: %%timeit
   .....: data = json.loads(json_data)
   .....: ret =  process_data(data) 
   .....: json.dumps(ret) 

I was wondering if there was a ruby (irb or pry) equivalent to them, or an idiomatic way to implement the equivalent in general (a timeit which accepts only a single method is not quite the same, it would be good to get the equivalent of the %timeit magic for any arbitrary block of code as in the later example).

like image 318
user3467349 Avatar asked Jun 07 '15 13:06

user3467349


1 Answers

Benchmark -
http://ruby-doc.org/stdlib-2.2.2/libdoc/benchmark/rdoc/Benchmark.html#method-c-benchmark
can help you with this.

Example:

require "benchmark"

how_long = Benchmark.measure do
  (1..100).each { |i| i }
end
puts how_long
like image 196
Michael Durrant Avatar answered Sep 24 '22 22:09

Michael Durrant