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

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


当前回答

方法是

$ > g++ -lpthread perform.c -o per
$ > time ./per

输出为>>

real    0m0.014s
user    0m0.010s
sys     0m0.002s

其他回答

如果您想要更精确,请使用%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

要逐行测量delta,请尝试用指针测量。

$ npm install -g gnomon
$ <your command> | gnomon --medium=1.0 --high=4.0 --ignore-blank --real-time=100

一个命令行实用程序,有点像moreutils的ts,用于将时间戳信息预先添加到另一个命令的标准输出中。对于长时间运行的流程非常有用,因为您需要记录花费如此长时间的事情。

还可以使用——high和/或——medium选项指定以秒为单位的长度阈值,超过该阈值,gnomon将以红色或黄色突出显示时间戳。你还可以做一些其他的事情。

方法是

$ > g++ -lpthread perform.c -o per
$ > time ./per

输出为>>

real    0m0.014s
user    0m0.010s
sys     0m0.002s

如果您打算以后使用时间来计算,请学习如何使用/usr/bin/time的-f选项来输出节省时间的代码。下面是我最近使用的一些代码,用于获取和排序整个班级的学生程序的执行时间:

fmt="run { date = '$(date)', user = '$who', test = '$test', host = '$(hostname)', times = { user = %U, system = %S, elapsed = %e } }"
/usr/bin/time -f "$fmt" -o $timefile command args...

后来我将所有$timefile文件连接起来,并将输出输出到Lua解释器中。你可以用Python或bash或任何你喜欢的语法做同样的事情。我喜欢这个技巧。

#!/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"