Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benchmarking a ruby operation that returns a value

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?

like image 508
justingordon Avatar asked Nov 20 '11 08:11

justingordon


1 Answers

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
like image 194
Miikka Avatar answered Nov 18 '22 04:11

Miikka