打印经过时间的秒三的尾部位数 [英] Print elapsed time in secs with three trailing digits
问题描述
有关框架我写,我想衡量一块(bash)的code多少需要执行,然后打印所用的时间以秒为单位。
For a framework I'm writing I would like to measure how much a piece of (bash) code takes to execute and then print the elapsed time in seconds.
有关测量,我做到以下几点:
For measuring, I do the following:
start=$(date +%s%N)
# do something here
elapsed_time=$(($(date +%s%N) - start))
这给了我经过毫微秒串接经过秒。如果我现在乘以1000000把这个,我会在毫秒时间
This gives me the elapsed seconds concatenated with the elapsed nanos. If I now divide this by 1000000, I'll get the time in ms
elapsed_time_in_ms=$(($elapsed time / 1000000))
这是所有好的,似乎工作,但真正的问题是,我想打印格式为:
This is all nice and seems to work but the real problem is that I want to print it in this format:
12.789s
,其中前。
是秒,小数点后是毫秒值的最后3位数字。
where before the .
are the seconds and after the dot are last 3 digits of the ms value.
我将如何实现这样的事情?
How would I achieve something like that?
修改
我知道时间很可能没有多大用处的,我还是想实现这个(即使只是化妆品的原因: - )。)
I am aware that the time would probably not of much use, still I would like to implement this (even if only for cosmetic reasons :-)).
编辑2
对于任何人面临同样的问题:
For anyone facing the same problem:
在最后,我选择了使用时间,因为它不需要叉,似乎是最便携的解决方案。
In the end I've chosen to use time as it doesn't require a fork and seems to be the most portable solution.
有一个看是
函数和全局 total_elapsed_time
变量的此处看到我是如何实现这一点。
Have a look at the it
function and the global total_elapsed_time
variable here to see how I implemented this.
推荐答案
您可以使用 BC
命令:
elapsed_time_in_ms=$(echo "scale=3;$elapsed_time/1000000" | bc)
的比例
基本设置后,你想要的位数的。
The scale
basically sets the number of digits you want after the .
这篇关于打印经过时间的秒三的尾部位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!