Forum: Ruby How to time the duration of a script.

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
68aaf297e62e0f78913a10694d8a8265?d=identicon&s=25 Oscar Gon (muychingon)
on 2005-12-12 23:52
If I wanted to find something like the "time" feature on shell...

where you can do:

time ls

and it will tell you how long it took to execute...

How would I do this in Ruby or what is the packaged that can do this for
me?  I want it to kick off as soon as the script gets called and just
print the time taken to execute at the end of the script.
Fe9b2d0628c0943af374b2fe5b320a82?d=identicon&s=25 Eero Saynatkari (rue)
on 2005-12-12 23:58
Oscar Gonzalez wrote:
> If I wanted to find something like the "time" feature on shell...
>
> where you can do:
>
> time ls
>
> and it will tell you how long it took to execute...
>
> How would I do this in Ruby or what is the packaged that can do this for
> me?  I want it to kick off as soon as the script gets called and just
> print the time taken to execute at the end of the script.

Well, you can actually use 'time my.rb' :)

Within ruby, you can use Benchmark (in stdlib):

 require 'benchmark'

 Benchmark.bm {|bench|
   bench.report { do_something_here }
 }

Another popular idiom seems to be the classic:

 start = Time.now

 # Do something

 duration = Time.now - start


E
Cb48ca5059faf7409a5ab3745a964696?d=identicon&s=25 unknown (Guest)
on 2005-12-13 00:29
(Received via mailing list)
On Tue, 13 Dec 2005, Oscar Gonzalez wrote:

> print the time taken to execute at the end of the script.
harp:~ > cat elapsed.rb
   BEGIN{ $start_time = Time::now.to_f }
   END{ $end_time = Time::now.to_f; puts "#{ $0 } elapsed: #{ $end_time
- $start_time} }" }

   harp:~ > cat a.rb
   sleep 2 and p 42

   harp:~ > ruby -r elapsed a.rb
   42
   a.rb elapsed: 1.99891686439514 }

or

   harp:~ > cat a.rb
   #!/usr/bin/env ruby
   sleep 2 and p 42

   harp:~ > RUBYOPT="-relapsed" ./a.rb
   42
   ./a.rb elapsed: 1.99908494949341 }

hth.

-a
This topic is locked and can not be replied to.