How do I measure duration in seconds in a shell script?

前端 未结 7 514
感情败类
感情败类 2020-12-07 22:02

I wish to find out how long an operation takes in a Linux shell script. How can I do this?

7条回答
  •  太阳男子
    2020-12-07 22:41

    GNU time

    I'm also a big fun of the GNU time command: https://www.gnu.org/software/time/ which offers some important options compared to the time Bash built-in.

    Sample usage:

    env time --format '%e' --output time.log sleep 1
    

    Output:

    1.00
    

    Explanation:

    • env: to find /usr/bin/time instead of the Bash built-in

    • --format '%e': print time in seconds, see man time.

      This is often what I want when benchmarking: a single number rather than minutes + seconds.

    And an important pattern I often use is:

    bench-cmd() (
      logfile=time.log
      echo "cmd $@" >> "$logfile"
      printf 'time ' >> "$logfile"
      bench_cmd="env time --append --format '%e' --output '$logfile' $@"
      eval "$bench_cmd"
      echo >> "$logfile"
    )
    
    rm -f time.log
    bench-cmd sleep 1
    bench-cmd sleep 2
    bench-cmd sleep 3
    cat time.log
    

    GitHub upstream.

    Output:

    cmd sleep 1
    time 1.00
    
    cmd sleep 2
    time 2.00
    
    cmd sleep 3
    time 3.00
    

    Explanation:

    • --output: output the time to a file.

      By default, the output goes to stderr, so this option is important to separate the timing from the stderr of the command.

    • --append: append to the file instead of overwriting.

      This allows me to concentrate the entire benchmark output in a single file.

提交回复
热议问题