简单的计时器,用于测量操作完成的秒数

Mic*_*l M 7 bash freebsd

我运行自己的脚本,每晚将数据库转储到文件中.
我想计算转储每个数据库所需的时间(以秒为单位),所以我试图编写一些函数来帮助我实现它,但是我遇到了问题.

我不是bash脚本的专家,所以如果我做错了,就这么说,理想情况下建议替代,请.

这是脚本:

#!/bin/bash

declare -i time_start

function get_timestamp {
        declare -i time_curr=`date -j -f "%a %b %d %T %Z %Y" "\`date\`" "+%s"`
        echo "get_timestamp:" $time_curr
        return $time_curr
}

function timer_start {
        get_timestamp
        time_start=$?
        echo "timer_start:" $time_start
}

function timer_stop {
        get_timestamp
        declare -i time_curr=$?
        echo "timer_stop:" $time_curr
        declare -i time_diff=$time_curr-$time_start

        return $time_diff
}

timer_start
sleep 3
timer_stop
echo $?
Run Code Online (Sandbox Code Playgroud)

代码应该是非常不言自明的.echo命令仅用于调试.
我希望输出是这样的:

$ bash timer.sh
get_timestamp: 1285945972
timer_start: 1285945972
get_timestamp: 1285945975
timer_stop: 1285945975
3
Run Code Online (Sandbox Code Playgroud)

现在不幸的是,情况并非如此.我得到的是:

$ bash timer.sh
get_timestamp: 1285945972
timer_start: 116
get_timestamp: 1285945975
timer_stop: 119
3
Run Code Online (Sandbox Code Playgroud)

如您所见,本地var time_curr从命令获取的值是有效的时间戳,但返回此值会使其更改为0到255之间的整数.

有人可以向我解释为什么会这样吗?

PS.这显然只是我的计时器测试脚本,没有任何其他逻辑.


UPDATE 只是要非常清楚,我想这是一个bash脚本非常类似的一部分这一个,在这里我想衡量每个循环周期.

除非我能用它做time,否则请建议一个解决方案.

Ale*_*sky 21

你不需要做这一切.只需time <yourscript>在shell中运行.


mob*_*mob 3

$?用于保存命令的退出状态,只能保存 0 到 255 之间的值。如果传递此范围之外的退出代码(例如,在调用 的 C 程序中exit(-1)),shell 仍将收到该范围内的值并进行$?相应设置。

作为解决方法,您可以在 bash 函数中设置不同的值:

function get_timestamp {
        declare -i time_curr=`date -j -f "%a %b %d %T %Z %Y" "\`date\`" "+%s"`
        echo "get_timestamp:" $time_curr
        get_timestamp_return_value=$time_curr
}

function timer_start {
        get_timestamp
        #time_start=$?
        time_start=$get_timestamp_return_value
        echo "timer_start:" $time_start
}

...
Run Code Online (Sandbox Code Playgroud)