I want to measure the execution time of the function in ruby.How do you measure it?

Asked 2 years ago, Updated 2 years ago, 34 views

I want to know how to measure the execution time in ruby

ruby

2022-09-22 12:51

2 Answers

You can use Time.now.

start = Time.now
a = 0
(1..10000).each do
    a = 0
end
finish = Time.now

puts(finish - start)

Try running the code.


2022-09-22 12:51

You can also use the benchmark module in the ruby.

require 'benchmark'

n = 50000
Benchmark.bm(7) do |x|
  x.report("for:")   { for i in 1..n; a = "1"; end }
  x.report("times:") { n.times do   ; a = "1"; end }
  x.report("upto:")  { 1.upto(n) do ; a = "1"; end }
end

Note: http://ruby-doc.org/stdlib-1.9.3/libdoc/benchmark/rdoc/Benchmark.html


2022-09-22 12:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.