计算帧率、每秒过多少次

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

输出:

相关推荐
少司府几秒前
C++基础入门:类和对象(中)
c语言·开发语言·c++·类和对象·运算符重载·默认成员函数
王老师青少年编程7 分钟前
csp信奥赛c++之状压枚举
数据结构·c++·算法·csp·信奥赛·csp-s·状压枚举
gogogo出发喽13 分钟前
使用Pear Admin Flask
后端·python·flask
与虾牵手18 分钟前
Python asyncio 踩了一周坑,我把能犯的错全犯了一遍
python
飞Link22 分钟前
LangGraph 核心架构解析:节点 (Nodes) 与边 (Edges) 的工作机制及实战指南
java·开发语言·python·算法·架构
资深设备全生命周期管理1 小时前
EXE Ver 适用于 未安装Python 以及包的Windows OS
python
Lyyaoo.1 小时前
【Java基础面经】Java 反射机制
java·开发语言·python
广州山泉婚姻1 小时前
VSCode中切换Python虚拟环境失败的原因
python
Ulyanov1 小时前
从零构建现代化Python音频播放器:ttk深度应用与皮肤系统设计
python·架构·音视频·数据可视化
ysa0510301 小时前
斐波那契上斐波那契【矩阵快速幂】
数据结构·c++·笔记·算法