下面是使用 Golang 实现定时器的代码:

package main

import (
	"fmt"
	"math"
	"time"
)

func main() {
	totalFrames := 10
	totalDuration := 5 // seconds

	averageDuration := math.Ceil(float64(totalDuration) / float64(totalFrames) * 1000) // average duration per frame in milliseconds
	fmt.Println("Average Duration (ms):", averageDuration)

	averageDurationMicro := averageDuration * 1000 // average duration per frame in microseconds
	fmt.Println("Average Duration (µs):", averageDurationMicro)

	for i := 0; i < totalFrames; i++ {
		fmt.Println("Sending frame", i+1)
		time.Sleep(time.Duration(averageDurationMicro) * time.Microsecond)
	}
}

在上面的代码中,我们将每帧的平均时长(毫秒)计算为 math.Ceil(float64(totalDuration) / float64(totalFrames) * 1000)。然后,我们将平均时长转换为微秒,以便使用 time.Sleep 函数等待指定的微秒数发送每帧的数据。

请注意,由于计算平均时长时使用的是 math.Ceil 函数,所以实际发送的每帧的时长可能会略长于平均时长。

Golang 定时器:使用 time.Sleep 发送数据帧并计算平均时长

原文地址: https://www.cveoy.top/t/topic/p0EI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录