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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With