bash 如何在bash脚本中以毫秒为单位获取经过的时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4456546/
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-09-17 23:06:32  来源:igfitidea点击:

How to get the elapsed time in milliseconds in a bash script?

bashshelltime

提问by Tony Stark

I tried using t1=$(date +%s%N)to get the time in nanoseconds, but I kept in getting this error:

我尝试使用t1=$(date +%s%N)以纳秒为单位获取时间,但我一直收到此错误:

./script.sh: line 10: 1292460931N: value too great for base (error token is "1292460931N")

I looked up online and it seems that you can use the "time" command, however I can't find a good example of using the time command. Any help would be appreciated :)

我在网上查了一下,似乎可以使用“time”命令,但是我找不到使用 time 命令的好示例。任何帮助,将不胜感激 :)

采纳答案by Charlie Martin

Okay, a couple of things here.

好的,这里有几件事。

First, not a lot of systems can give you a time that actually accurate to nanoseconds anyway.

首先,无论如何,没有多少系统可以为您提供实际精确到纳秒的时间。

Now, using time, either as /usr/bin/timeor the shell builtin (bash: help time) is very easy. If the command you want to time is foo1, then

现在,使用时间,无论是 as/usr/bin/time还是 shell 内置 (bash:)help time都非常容易。如果您要计时的命令是foo1,则

$ time foo

will return the elapsed time as three lines on stderr

将在 stderr 上以三行形式返回经过的时间

real 0m0.001s
user 0m0.000s
sys  0m0.000s

which you can use any way you like.

你可以使用任何你喜欢的方式。

If you want to get a better, more accurate timing, execute the command many times. This can be as simple as writing a short loop

如果您想获得更好、更准确的计时,请多次执行该命令。这可以像编写一个短循环一样简单

time for i in 0 1 2 3 4; do foo; done

will do foofive times and give you the total time. You probably want to do more than 5 iterations, so you'd probably want a counter and a while loop or the like.

会做foo五次,给你总时间。您可能想要进行 5 次以上的迭代,因此您可能需要一个计数器和一个 while 循环等。

回答by Ben Hymanson

The datecommand you're using doesn't support %Nso your output is literally 1292460931N. I tried it on Linux and it worked, but on FreeBSD I see the results you got. Run that date command in a shell and see what comes out. Is it possible you're using busybox? Its cut-down date command also omits %Nbut the version I just tried gave me 1292463535%N.

date您使用的命令不支持,%N因此您的输出实际上是1292460931N. 我在 Linux 上尝试过它并且有效,但是在 FreeBSD 上我看到了你得到的结果。在 shell 中运行该 date 命令并查看结果。有可能你正在使用busybox吗?它的缩减日期命令也省略了,%N但我刚刚尝试的版本给了我1292463535%N.