计算帧率、每秒过多少次

1、c++

cpp 复制代码
#include <iostream>
#include <opencv2/opencv.hpp>
#include <string>
#include <thread>
#include <atomic>

using namespace std;

const int NUM_THREADS = 1; // 线程数量

std::atomic<int> frameCounts[NUM_THREADS];  // 每个线程的帧计数
std::atomic<bool> running(true);            // 控制定时器的运行状态
std::mutex printMutex;

// 定时器函数,记录每个线程的FPS
void timer(int threadIndex) {
	while (running) {
		// 等待1秒
		std::this_thread::sleep_for(std::chrono::seconds(1));

		// 打印并重置当前线程的帧数
		int fps = frameCounts[threadIndex].exchange(0);
		{
			std::lock_guard<std::mutex> lock(printMutex);
			std::cout << "Thread " << threadIndex << " FPS: " << fps << std::endl;
		}
	}
}

int main() {
	std::thread t(timer, 0);
	t.detach();
	while (true) {
		frameCounts[0]++;
	}
	
	system("pause");
	return 0;
}

输出:

2、Python

python 复制代码
from multiprocessing import Process, Lock, Value
import time

class Timer(Process):
    def __init__(self, lock, crt_time, last_time):
        super().__init__()
        self.current_time = current_time
        self.last_time = last_time
        self.lock = lock
    
    def run(self):
        while True:
            # 等待1s
            time.sleep(1)
            with self.lock:
                self.last_time.value = self.current_time.value
                print('----------num----------:', self.last_time.value)
                self.current_time.value = 0
            

if __name__ == '__main__':
    lock = Lock()
    # 使用 Value 创建共享变量
    current_time = Value('i', 0)  # 'i' 表示整数类型
    last_time = Value('i', 0)

    timer = Timer(lock, current_time, last_time)
    timer.start()
    while True:
        with lock:
            timer.current_time.value += 1

输出:

相关推荐
Mr_WangAndy1 小时前
C++_chapter13_C++并发与多线程_多线程概念,死锁,unique_lock(),lock_guard()使用
c++·lock·死锁·并发与多线程·unlock·lock_guard·unique_lock
小欣加油1 小时前
leetcode 946 验证栈序列
c++·算法·leetcode·职场和发展
神仙别闹1 小时前
基于QT(C++) 实现哈夫曼压缩(多线程)
java·c++·qt
Python私教2 小时前
Python 开发环境安装与配置全指南(2025版)
开发语言·python
百锦再2 小时前
第12章 测试编写
android·java·开发语言·python·rust·go·erlang
无敌最俊朗@2 小时前
C++ 并发与同步速查笔记(整理版)
开发语言·c++·算法
熠熠仔2 小时前
QGIS 3.34+ 网络分析基础数据自动化生成:从脚本到应用
python·数据分析
测试19982 小时前
Appium使用指南与自动化测试案例详解
自动化测试·软件测试·python·测试工具·职场和发展·appium·测试用例
神仙别闹2 小时前
基于 C++和 Python 实现计算机视觉
c++·python·计算机视觉
hongjianMa3 小时前
【论文阅读】Hypercomplex Prompt-aware Multimodal Recommendation
论文阅读·python·深度学习·机器学习·prompt·推荐系统