计算帧率、每秒过多少次

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

输出:

相关推荐
曲幽5 分钟前
我用fastapi-scaff搭了个项目,两天工期缩到两小时,老板以为我开挂了
python·api·fastapi·web·celery·cli·db·alembic·fastapi-scaff
半点闲8 分钟前
入门 SQLAlchemy 教程:从 0 到 1 创建数据库
数据库·python·sqlite·sqlalchemy
好家伙VCC12 分钟前
# 发散创新:基于事件驱动架构的实时日志监控系统设计与实现在现代分布式系统中,**事件驱动编程模型**正
java·python·架构
测试199814 分钟前
postman接口测试详解
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
SuniaWang14 分钟前
Java 17实战:Record与密封类的黄金搭档
java·开发语言·python
时光不写代码16 分钟前
修复 pytest-asyncio 事件循环冲突:完整解决方案
python·pytest·fastapi
2401_8274999916 分钟前
python项目实战10-网络机器人03
开发语言·python·php
小江的记录本24 分钟前
【Transformer架构】Transformer架构核心知识体系(包括自注意力机制、多头注意力、Encoder-Decoder结构)
java·人工智能·后端·python·深度学习·架构·transformer
7年前端辞职转AI25 分钟前
Python 注释
python·编程语言
AIminminHu28 分钟前
OpenGL渲染与几何内核那点事-项目实践理论补充(三-1-(3):番外篇-当你的CAD打开“怪兽级”STL时:从内存爆炸到零拷贝的极致优化)
开发语言·c++·线程·多线程