# How to time the duration of a script

**URL:** <https://www.ruby-forum.com/t/how-to-time-the-duration-of-a-script/50094>\
**Category:** Ruby\
**Created:** [December 12, 2005, 11:52pm UTC](https://www.ruby-forum.com/t/how-to-time-the-duration-of-a-script/50094 "2005-12-12T23:52:24Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![muychingon](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/8491ac/32.png) [@muychingon](https://www.ruby-forum.com/u/muychingon)\
**Post date:** [December 12, 2005, 11:52pm UTC](https://www.ruby-forum.com/t/how-to-time-the-duration-of-a-script/50094/1 "2005-12-12T23:52:24Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![muychingon](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/8491ac/32.png) [@muychingon](https://www.ruby-forum.com/u/muychingon)\
**Post date:** [December 12, 2005, 11:58pm UTC](https://www.ruby-forum.com/t/how-to-time-the-duration-of-a-script/50094/2 "2005-12-12T23:58:46Z")

</div>

Oscar G. 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

---

<div class="post-metadata">

**Author:** ![muychingon](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/8491ac/32.png) [@muychingon](https://www.ruby-forum.com/u/muychingon)\
**Post date:** [December 13, 2005, 12:29am UTC](https://www.ruby-forum.com/t/how-to-time-the-duration-of-a-script/50094/3 "2005-12-13T00:29:21Z")

</div>

On Tue, 13 Dec 2005, Oscar G. 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} }" }

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
