Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This thread shows how to measure the time it takes to run a script. In my case, I am interested in measuring time between two points within a script. Here is an example of how I would like to use this:

start_measuring_time
Line 1
Line 2
..
Line N
stop_measuring_time
show_elapsed_time

I would like the displayed time to be human readable (secs, min, hours, days, etc.), if possible. Any ideas how to do this?

share|improve this question

2 Answers 2

up vote 7 down vote accepted

You can use date util:

#!/bin/bash

start_measuring_time() {
  read s1 s2 < <(date +'%s %N')
}

stop_measuring_time() {
  read e1 e2 < <(date +'%s %N')
}

show_elapsed_time() {
  echo "$((e1-s1)) seconds, $((e2-s2)) nanoseconds"
}

start_measuring_time
sleep 2
stop_measuring_time
show_elapsed_time
share|improve this answer
    
This will produce errors: the beginning and ending times need to be interpreted as seconds + nanoseconds together, not separately - you can get things like negative values otherwise. –  rozcietrzewiacz Sep 1 '11 at 11:23
    
See my answer to this question for a way to solve this. –  rozcietrzewiacz Sep 1 '11 at 11:56

You could just use time:

time (
Line 1
Line 2
..
Line N
)

I think the output of time is human readable as is, but if your script is going to measure in days, etc., then check out man time for formatting options for the output.

share|improve this answer
    
Thanks @frabjous! I think I will accept @enzotib's answer because it allows me to measure time in general control flows (i.e. not just in linear flows). –  user815423426 Aug 12 '11 at 19:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.