【97】shell实现精确延时

#!/bin/bash

#使用date精确延时的函数,参数是毫秒
function precise_sleep_ms() {
    local duration_ms=$1

    # 将毫秒转换为秒
    local duration_sec=$(echo "scale=9; $duration_ms / 1000" | bc)
	duration_sec=$(printf "%.3f" "$duration_sec")
    # 计算结束时间点
    local end_time=$(echo "$(date +%s.%N) + $duration_sec" | bc)

    while [[ $(date +%s.%N) < $end_time ]]; do
        sleep 0.000001  # 使用更短暂的sleep减少CPU占用
    done
}
#使用date来获取到毫秒级别
function get_millisecond() {
	date +%Y-%m-%d' '%H:%M:%S.%N | cut -b 1-23
}

#延时length毫秒
function mt_sleep_ms() {
	local length=$1
	#延时$length毫秒
	if ! date +%N | grep -q '[0-9]\{9\}'; then
		#有些系统上的date命令可能不支持%N(纳秒),则使用不精确的sleep函数
		echo "Error: Your system's 'date' command does not support nanoseconds, use sleep cmd."
		sleep $length/1000
    else
		precise_sleep_ms $length
	fi
}
echo "test 5ms"
get_millisecond
mt_sleep_ms 5
get_millisecond
echo -e "\n"

echo "test 10ms"
get_millisecond
mt_sleep_ms 10
get_millisecond
echo -e "\n"

echo "test 100ms"
get_millisecond
mt_sleep_ms 100
get_millisecond
echo -e "\n"

echo "test 1000ms"
get_millisecond
mt_sleep_ms 1000
get_millisecond
echo -e "\n"

echo "test 5000ms"
get_millisecond
mt_sleep_ms 5000
get_millisecond
echo -e "\n"

echo "test 10000ms"
get_millisecond
mt_sleep_ms 10000
get_millisecond

运行结果如下,可以看出,5ms和10ms都不是特别准确,100ms完后准确点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

linjiasen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值