Anda di halaman 1dari 2

Measuring time within a script - Unix & Linux S...

https://unix.stackexchange.com/questions/1827...

Unix & Linux Stack Exchange works best with JavaScript enabled
sign up

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.

log in

tour

Take the 2-minute tour

help

Measuring time within a script


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?
/ shell-script

/ time

asked Aug 7 '11 at 19:08


user815423426
5,079

14

47

106

2 Answers
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

edited Aug 7 '11 at 19:54

answered Aug 7 '11 at 19:27


enzotib
15.9k

49

61

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,

1 din 2

13.12.2014 19:05

Measuring time within a script - Unix & Linux S...

https://unix.stackexchange.com/questions/1827...

Unix & Linux Stack Exchange works best with JavaScript enabled
answered Aug 7 '11 at 20:09
frabjous
2,872

20

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

2 din 2

13.12.2014 19:05

Anda mungkin juga menyukai