11
votes

The benchmark takes a block and returns the time: http://ruby-doc.org/stdlib-1.9.3/libdoc/benchmark/rdoc/Benchmark.html

require 'benchmark'
puts Benchmark.measure { "a"*1_000_000 }

What if you want to benchmark an operation and get both the return value and the elapsed time?

Or, stated another way, can a closure modify an object passed into it?

2

2 Answers

12
votes

A closure can modify objects in its scope, like this:

require 'benchmark'

a = nil
puts Benchmark.measure { a = "a" * 1_000_000 }
puts a.size

# =>   0.000000   0.000000   0.000000 (  0.004865)
# => 1000000
0
votes

With https://github.com/igorkasyanchuk/benchmark_methods

No more code like this:

t = Time.now
user.calculate_report
puts Time.now - t

Now you can do:

benchmark :calculate_report # in class

And just call your method

user.calculate_report