Bash script to calculate time elapsed

后端 未结 10 1678
被撕碎了的回忆
被撕碎了的回忆 2021-01-29 22:03

I am writing a script in bash to calculate the time elapsed for the execution of my commands, consider:

STARTTIME=$(date +%s)
#command block that takes time to c         


        
10条回答
  •  攒了一身酷
    2021-01-29 22:27

    You can use Bash's time keyword here with an appropriate format string

    TIMEFORMAT='It takes %R seconds to complete this task...'
    time {
        #command block that takes time to complete...
        #........
     }
    

    Here's what the reference says about TIMEFORMAT:

    The value of this parameter is used as a format string specifying how the timing information for pipelines prefixed with the time reserved word should be displayed. The ‘%’ character introduces an escape sequence that is expanded to a time value or other information. The escape sequences and their meanings are as follows; the braces denote optional portions.

    %%
    
        A literal ‘%’.
    %[p][l]R
    
        The elapsed time in seconds.
    %[p][l]U
    
        The number of CPU seconds spent in user mode.
    %[p][l]S
    
        The number of CPU seconds spent in system mode.
    %P
    
        The CPU percentage, computed as (%U + %S) / %R. 
    

    The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point may be specified; values of p greater than 3 are changed to 3. If p is not specified, the value 3 is used.

    The optional l specifies a longer format, including minutes, of the form MMmSS.FFs. The value of p determines whether or not the fraction is included.

    If this variable is not set, Bash acts as if it had the value

    $'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS'
    

    If the value is null, no timing information is displayed. A trailing newline is added when the format string is displayed.

提交回复
热议问题