Linux 在 shell 中获取程序执行时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/385408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 16:48:56  来源:igfitidea点击:

Get program execution time in the shell

linuxbashshell

提问by ???u

I want to execute something in a linux shell under a few different conditions, and be able to output the execution time of each execution.

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

I know I could write a perl or python script that would do this, but is there a way I can do it in the shell? (which happens to be bash)

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

采纳答案by Robert Gamble

Use the built-in timekeyword:

使用内置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.

Example:

例子:

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

回答by grepsedawk

You can get much more detailed information than the bash built-in time(which Robert Gamble mentions) using time(1). Normally this is /usr/bin/time.

time使用time(1)可以获得比 bash 内置(Robert Gamble 提到的)更详细的信息。通常这是/usr/bin/time.

Editor's note: To ensure that you're invoking the external utilitytimerather than your shell's timekeyword, invoke it as /usr/bin/time.
timeis a POSIX-mandated utility, but the only option it is required to support is -p.
Specific platforms implement specific, nonstandard extensions: -vworks with GNU's timeutility, as demonstrated below (the question is tagged linux); the BSD/macOS implementation uses -lto produce similar output - see man 1 time.

编者注:为确保您调用的是外部实用程序time而不是 shell 的time关键字,请将其调用为/usr/bin/time
timePOSIX 授权的实用程序,但它需要支持的唯一选项是-p.
特定平台实现特定的、非标准的扩展:-v使用GNUtime实用程序,如下所示(问题被标记为linux);BSD/macOS 实现用于-l产生类似的输出 - 请参阅man 1 time

Example of verbose output:

详细输出示例:


$ /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

回答by Norman Ramsey

If you intend to use the times later to compute with, learn how to use the -foption of /usr/bin/timeto output codethat saves times. Here's some code I used recently to get and sort the execution times of a whole classful of students' programs:

如果您打算稍后使用时间进行计算,请了解如何使用输出代码-f选项/usr/bin/time来节省时间。这是我最近用来获取和排序整类学生程序的执行时间的一些代码:

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...

I later concatenated all the $timefilefiles and pipe the output into a Lua interpreter. You can do the same with Python or bash or whatever your favorite syntax is. I love this technique.

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

回答by Robel Sharma

The way is

办法是

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

output is >>

输出是>>

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

回答by David

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

回答by Benoit Duffez

Should you want more precision, use %Nwith date(and use bcfor the diff, because $(())only handles integers).

如果您想要更高的精度,请使用%Nwith date(并bc用于差异,因为$(())只处理整数)。

Here's how to do it:

这是如何做到的:

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

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

Example:

例子:

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

Result:

结果:

Execution time: 0.104623 seconds

回答by Adriano Resende

For a line-by-line delta measurement, try gnomon.

对于逐行增量测量,请尝试gnomon

A command line utility, a bit like moreutils's ts, to prepend timestamp information to the standard output of another command. Useful for long-running processes where you'd like a historical record of what's taking so long.

一个命令行实用程序,有点像 moreutils 的 ts,用于将时间戳信息添加到另一个命令的标准输出中。对于需要长时间运行的历史记录的长时间运行的流程非常有用。

You can also use the --highand/or --mediumoptions to specify a length threshold in seconds, over which gnomon will highlight the timestamp in red or yellow. And you can do a few other things, too.

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

example

例子

回答by Eduardo Cuomo

You can use timeand subshell():

您可以使用timesubshel​​l()

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

Or in same shell {}:

或者在同一个 shell 中{}

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

回答by glenn Hymanman

If you only need precision to the second, you can use the builtin $SECONDSvariable, which counts the number of seconds that the shell has been running.

如果您只需要精确到秒,您可以使用内置$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

回答by tstorym

one possibly simple method ( that may not meet different users needs ) is the use of shell PROMPT.it is a simple solution that can be useful in some cases. You can use the bash prompting feature as in the example below:

一种可能简单的方法(可能无法满足不同用户的需求)是使用 shell PROMPT。它是一种在某些情况下很有用的简单解决方案。您可以使用 bash 提示功能,如下例所示:

export PS1='[\t \u@\h]$' 

The above command will result in changing the shell prompt to :

上述命令将导致将 shell 提示符更改为:

[HH:MM:SS username@hostname]$ 

Each time you run a command (or hit enter) returning back to the shell prompt, the prompt will display current time.

每次运行命令(或按 Enter 键)返回到 shell 提示时,提示都会显示当前时间。

notes:
1)beware that if you waited for sometime before you type your next command, then this time need to be considered, i.e the time displayed in the shell prompt is the timestamp when the shell prompt was displayed, not when you enter command. some users choose to hit Enter key to get a new prompt with a new timestamp before they are ready for the next command.
2)There are other available options and modifiers that can be used to change the bash prompt, refer to ( man bash ) for more details.

注意:
1)注意,如果你在输入下一个命令之前等待了一段时间,那么这个时间需要考虑,即shell提示符中显示的时间是shell提示符显示时的时间戳,而不是你输入命令时的时间戳。一些用户选择按 Enter 键以获得带有新时间戳的新提示,然后再准备下一个命令。
2)还有其他可用的选项和修饰符可用于更改 bash 提示,请参阅 ( man bash ) 了解更多详细信息。