计算帧率、每秒过多少次

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

输出:

相关推荐
闻哥17 分钟前
深入理解 Spring @Conditional 注解:原理与实战
java·jvm·后端·python·spring
茉莉玫瑰花茶28 分钟前
C++ 17 详细特性解析(4)
开发语言·c++·算法
小鸡吃米…29 分钟前
机器学习 - 堆叠集成(Stacking)
人工智能·python·机器学习
青春不朽51237 分钟前
Scikit-learn 入门指南
python·机器学习·scikit-learn
进击的小头1 小时前
FIR滤波器实战:音频信号降噪
c语言·python·算法·音视频
欧阳x天1 小时前
STL详解(九)—— stack和queue的模拟实现
开发语言·c++
乔江seven1 小时前
【python轻量级Web框架 Flask 】2 构建稳健 API:集成 MySQL 参数化查询与 DBUtils 连接池
前端·python·mysql·flask·web
dgaf1 小时前
【疯狂的往左】用 C 语言播放《下山》
c语言·c++
卷卷的小趴菜学编程1 小时前
项目篇----仿tcmalloc的内存池设计(central cache篇)
c++·tcmalloc·内存池·central cache
2301_810730101 小时前
python第四次作业
数据结构·python·算法