脚本
#!/bin/bash
#set -x
task=result_get_time
mkdir -p ${task}
total_time=0
function getTiming() {
local start=$1
local end=$2
local start_s=`echo $start| cut -d '.' -f 1`
local start_ns=`echo $start| cut -d '.' -f 2`
local end_s=`echo $end| cut -d '.' -f 1`
local end_ns=`echo $end| cut -d '.' -f 2`
local time_micro=$(( (10#$end_s-10#$start_s)*1000000 + (10#$end_ns/1000 - 10#$start_ns/1000) ))
local time_ms=`expr $time_micro/1000 | bc `
local time_s_single=`echo "scale=5;${time_ms} / 1000 / 100" | bc | awk '{printf "%.3f", $0}'`
total_time=`echo "scale=5;${total_time} + ${time_s_single}" | bc | awk '{printf "%.3f", $0}'`
echo "stage ${3}" >> ${task}/time_log
echo "$time_micro microseconds" >> ${task}/time_log
echo "$time_ms ms" >> ${task}/time_log
echo "$time_s_single s/wav" >> ${task}/time_log
}
begin_time=`date +%s.%N`
sleep 1
end_time=`date +%s.%N`
getTiming $begin_time $end_time get_time_1
echo "total_time="${total_time} | tee -a get_time.log
begin_time=`date +%s.%N`
sleep 3
end_time=`date +%s.%N`
getTiming $begin_time $end_time get_time_3
echo "total_time="${total_time} | tee -a get_time.log
用法
./run.sh 或 bash run.sh
效果
获取一段代码的执行时间,累计到总执行时间,输出到标准输出,同时追加到文件
bc计算精度用scale控制,输出精度用awk控制