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

前端 未结 7 515
感情败类
感情败类 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:21

    Many of the answers mention $SECONDS, but that variable is actually even better than they realize:

    Assignment to this variable resets the count to the value assigned, and the expanded value becomes the value assigned plus the number of seconds since the assignment.

    This means you can simply query this variable directly at the end of your script to print the elapsed time:

    #!/usr/bin/env bash
    
    # Do stuff...
    
    echo "Script finished in $SECONDS seconds."
    

    You can also time smaller sections like so:

    #!/usr/bin/env bash
    
    # Do stuff
    
    SECONDS=0
    
    # Do timed stuff...
    
    echo "Timed stuff finished in $SECONDS seconds."
    
    0 讨论(0)
  • 2020-12-07 22:23

    Using the time command, as others have suggested, is a good idea.

    Another option is to use the magic built-in variable $SECONDS, which contains the number of seconds since the script started executing. You can say:

    START_TIME=$SECONDS
    dosomething
    ELAPSED_TIME=$(($SECONDS - $START_TIME))
    

    I think this is bash-specific, but since you're on Linux, I assume you're using bash.

    0 讨论(0)
  • 2020-12-07 22:23

    Use the time command. time ls /bin.

    0 讨论(0)
  • 2020-12-07 22:23

    Here is the script to find the time elapsed in milliseconds. Replace the sleep 60 line with the code you want to execute.

    a=0
    while [ $a -lt 10 ]
    do
    START_TIME=`echo $(($(date +%s%N)/1000000))`
    sleep 3
    END_TIME=`echo $(($(date +%s%N)/1000000))`
    ELAPSED_TIME=$(($END_TIME - $START_TIME))
    echo $ELAPSED_TIME
    if [ $a -eq 10 ]
    then
      break
    fi
    a=`expr $a + 1`
    done
    
    0 讨论(0)
  • 2020-12-07 22:28

    Try following example:

    START_TIME=$SECONDS
    # do something
    sleep 65
    
    ELAPSED_TIME=$(($SECONDS - $START_TIME))
    
    echo "$(($ELAPSED_TIME/60)) min $(($ELAPSED_TIME%60)) sec"    
    #> 1 min 5 sec
    
    0 讨论(0)
  • 2020-12-07 22:38

    Just to help anyone like me that receive an error:

     arithmetic expression: expecting primary: "-"
    

    Check your shellscript that shall start with:

    #!/bin/bash
    

    Cheers!

    0 讨论(0)
提交回复
热议问题