Bash shell script for 100 iterations and log time taken

后端 未结 5 1307
长发绾君心
长发绾君心 2020-12-15 07:27

How do I run 100 iterations using a bash shell script? I want to know how long it will take to execute one command (start and end time). I want to keep track which iteratio

5条回答
  •  孤街浪徒
    2020-12-15 07:42

    You can try with:

    for i in {1..100}; do time some_script.sh; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'
    

    Explanation

    • The for loop runs some_script.sh 100 times, measuring its execution time with time
    • The stderr of the for loop is redirected to stdout, this is to capture the output of time so we can grep it
    • grep ^real is to get only the lines starting with "real" in the output of time
    • sed is to delete the beginning of the line up to minutes part (in the output of time)
    • For each line, awk adds to the sum, so that in the end it can output the average, which is the total sum, divided by the number of input records (= NR)

    Limitations

    The snippet assumes that the running time of some_script.sh is less than 1 minute, otherwise it won't work at all. Depending on your system, the time builtin might work differently. Another alternative is to use the time command /usr/bin/time instead of the bash builtin.

    Note: This script was extracted from here.

提交回复
热议问题