控制1秒30帧的视频频率

复制代码
#include <chrono>
#include <thread>

void controlFrameRate(std::chrono::milliseconds frameDuration) {
    auto startTime = std::chrono::high_resolution_clock::now();

    // Your drawing/rendering logic here

    auto endTime = std::chrono::high_resolution_clock::now();
    auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);

    std::this_thread::sleep_for(frameDuration - elapsedTime);
}

int main() {
    const int framesPerSecond = 30;
    const std::chrono::milliseconds frameDuration(1000 / framesPerSecond);

    while (true) {
        controlFrameRate(frameDuration);
    }

    return 0;
}

1秒30帧,1秒等于1000毫秒,所以用1000除以30,得到平均一帧多长时间frameDuration

当处理完一帧图片的时候,得到elapsedTime。如果elapsedTime小于frameDuration,这个时候要让程序暂停一下,即std::this_thread::sleep_for,让进程睡一会,然后再进行下一次的工作;如果elapsedTime大于frameDuration,这样应该达不到1秒30帧的频率

这样就能控制好,是1秒30帧的频率。

全部写在主函数里,是下面的代码逻辑

复制代码
#include <chrono>
#include <thread>

int main() {
    const int framesPerSecond = 30;
    const std::chrono::milliseconds frameDuration(1000 / framesPerSecond);

    while (true) {
        auto startTime = std::chrono::high_resolution_clock::now();

        // Your drawing/rendering logic here

        auto endTime = std::chrono::high_resolution_clock::now();
        auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);

        std::this_thread::sleep_for(frameDuration - elapsedTime);
    }

    return 0;
}
相关推荐
地平线开发者4 小时前
J6B vio scenario sample
算法
BothSavage16 小时前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn16 小时前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
烬羽17 小时前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
先吃饱再说1 天前
判断回文字符串,从一行代码到双指针优化
算法
黄敬峰1 天前
深入理解算法核心:从递归思想、数组扁平化到快速排序
算法
得物技术2 天前
从狂野代码到按目标生产:得物推荐 AI Harness 的工程化实践|AICon 演讲整理
人工智能·算法·架构
RTC实战笔记2 天前
实时互动数字人怎么做,才不是一个只会说话的视频?
音视频·数字人·rtc·数字人接入