在unix脚本中执行命令并计算时序[重复]


如果
2025-03-19 02:49:39 (4小时前)


我是bash脚本的新手。如何执行以下命令以捕获执行命令的时间。

我在数组变量中捕获了我的交易。然后,我正在完成交易……

2 条回复
  1. 0# 不想吃东西 | 2019-08-31 10-32



    你可以用

    date +%s

    在操作之前和之后找到以秒为单位的时差。例如 :




    1. array=( 5 10 15 20 25 )
      for val in ${array[@]}”
      do
      starttime=$(date +%s)
      sleep $val # sleeping for ‘$val’ seconds in each iteration

    2. you should replace the above with the actual process.

      endtime=$(date +%s)
      echo Time taken for the process is $((endtime-starttime))s
      done

    3. </code>


    这会给




    1. Time taken for the process is 5s
      Time taken for the process is 10s
      Time taken for the process is 15s
      Time taken for the process is 20s
      Time taken for the process is 25s

    2. </code>


    但是,我应该承认它可以提供几秒钟的精度。





    +%s

    格式字符串需要特别提及。该

    date

    manpage说:




    自1970-01-01 00:00:00 UTC以来的%s秒




    本质上,我们只计算过去参考点的经过时间(以秒为单位),然后计算结束时间和开始时间之间的差异。一旦你有时间在几秒钟内,使用明确定义的数学隔离小时和分钟。



    正如@ChalresDuffy指出的那样

    这个

    评论,你可以使用

    $ SECONDS

    内部变量来计算时差。也,

    $ EPOCHREALTIME

    如果需要微秒级的粒度,可以使用。


登录 后才能参与评论