我想在一些不同的条件下在linux shell中执行一些东西,并且能够输出每次执行的执行时间。

我知道我可以写一个perl或python脚本,可以做到这一点,但有一种方法我可以在shell中做到这一点吗?(恰好是bash)


当前回答

你可以使用time和subshell ():

time (
  for (( i=1; i<10000; i++ )); do
    echo 1 >/dev/null
  done
)

或者在同一个shell{}中:

time {
  for (( i=1; i<10000; i++ )); do
    echo 1 >/dev/null
  done
}

其他回答

使用内置的time关键字:

$ help time

time: time [-p] PIPELINE
    Execute PIPELINE and print a summary of the real time, user CPU time,
    and system CPU time spent executing PIPELINE when it terminates.
    The return status is the return status of PIPELINE.  The `-p' option
    prints the timing summary in a slightly different format.  This uses
    the value of the TIMEFORMAT variable as the output format.

例子:

$ time sleep 2
real    0m2.009s
user    0m0.000s
sys     0m0.004s

如果您想要更精确,请使用%N和date(并使用bc作为diff,因为$(())只处理整数)。

以下是如何做到这一点:

start=$(date +%s.%N)
# do some stuff here
dur=$(echo "$(date +%s.%N) - $start" | bc)

printf "Execution time: %.6f seconds" $dur

例子:

start=$(date +%s.%N); \
  sleep 0.1s; \
  dur=$(echo "$(date +%s.%N) - $start" | bc); \
  printf "Execution time: %.6f seconds\n" $dur

结果:

Execution time: 0.104623 seconds
#!/bin/bash
START=$(date +%s)
# do something
# start your script work here
ls -R /etc > /tmp/x
rm -f /tmp/x
# your logic ends here
END=$(date +%s)
DIFF=$(( $END - $START ))
echo "It took $DIFF seconds"

如果您只需要精确到秒,您可以使用内置的$SECONDS变量,该变量计算shell已经运行的秒数。

while true; do
    start=$SECONDS
    some_long_running_command
    duration=$(( SECONDS - start ))
    echo "This run took $duration seconds"
    if some_condition; then break; fi
done

您可以获得比bash内置时间(即time(1), Robert Gamble提到过)更详细的信息。通常这是/usr/bin/时间

编者按: 为了确保您调用的是外部实用程序time而不是shell的time关键字,请以/usr/bin/time来调用它 time是posix强制的实用程序,但它需要支持的唯一选项是-p。 特定的平台实现特定的、非标准的扩展:-v与GNU的time实用程序一起工作,如下所示(问题被标记为linux);BSD/macOS实现使用-l来产生类似的输出-参见man 1次。

详细输出示例:

$ /usr/bin/time -v sleep 1
       Command being timed: "sleep 1"
       User time (seconds): 0.00
       System time (seconds): 0.00
       Percent of CPU this job got: 1%
       Elapsed (wall clock) time (h:mm:ss or m:ss): 0:01.05
       Average shared text size (kbytes): 0
       Average unshared data size (kbytes): 0
       Average stack size (kbytes): 0
       Average total size (kbytes): 0
       Maximum resident set size (kbytes): 0
       Average resident set size (kbytes): 0
       Major (requiring I/O) page faults: 0
       Minor (reclaiming a frame) page faults: 210
       Voluntary context switches: 2
       Involuntary context switches: 1
       Swaps: 0
       File system inputs: 0
       File system outputs: 0
       Socket messages sent: 0
       Socket messages received: 0
       Signals delivered: 0
       Page size (bytes): 4096
       Exit status: 0