【发布时间】:2014-03-12 08:41:36
【问题描述】:
我想知道是否有办法从 Mac OS 上的 shell 脚本中获取以毫秒为单位的时间。
我需要它来计算某些查询的运行时间。
现在我只能以秒为单位获得时间:
Start=`date +%s`
End =`date +%s`
Time=$Start-$End
【问题讨论】:
标签: macos shell time milliseconds
我想知道是否有办法从 Mac OS 上的 shell 脚本中获取以毫秒为单位的时间。
我需要它来计算某些查询的运行时间。
现在我只能以秒为单位获得时间:
Start=`date +%s`
End =`date +%s`
Time=$Start-$End
【问题讨论】:
标签: macos shell time milliseconds
只需使用“时间”命令:
time something
可以是 shell 或命令(查找等)
“实际”时间是您想要的总经过时间,包括毫秒
【讨论】:
您可以使用基准测试工具hyperfine (https://github.com/sharkdp/hyperfine)。
它比time 更精细,默认情况下会多次运行您的命令,并为您提供平均运行时间、偏差、最小值和最大值。
简单使用
hyperfine your_command
结果如下所示 (result of hyperfine 'sleep 0.5'):
bash-3.2$ hyperfine 'sleep 0.5'
Benchmark #1: sleep 0.5
Time (mean ± σ): 505.6 ms ± 1.5 ms [User: 0.8 ms, System: 1.2 ms]
Range (min … max): 503.1 ms … 508.8 ms 10 runs
有一个警告,最少运行次数为 2 (hyperfine -r 2 'your command')。
安装
Hyperfine 可以通过 Homebrew 安装:
brew install hyperfine
欲了解更多信息,请参阅:https://github.com/sharkdp/hyperfine#on-macos
【讨论】:
由于Mac OS是类BSD系统,它的date不支持你需要的%N参数。
您可以考虑安装GNU Core Utils。
它将允许您在the usual Linux way 中获取时间。
我想,time something 命令也会以毫秒为单位输出结果。
【讨论】: