计算帧率、每秒过多少次

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

输出:

相关推荐
凌盛羽4 分钟前
在MDK-ARM编译后用python解析map文件在编译窗口输出Flash和RAM使用及剩余情况
arm开发·python·stm32·单片机·mysql·链表·esp32
GuokLiu7 分钟前
260331-OpenWebUI统计所有Chat的对话字符个数
python
哈伦20198 分钟前
Python 生成随机数
python·机器学习·pandas
王璐WL10 分钟前
【C++】经典且易错的题
c++
zzwq.10 分钟前
魔法方法 __init__ 与 __new__ 的区别与使用场景
python
feasibility.13 分钟前
OpenCV图像滤波算法应用:常见滤波器的原理与效果对比(含c++/python代码与中文显示)
c++·opencv·算法
傻啦嘿哟19 分钟前
如何使用 Python 操作 Excel 图片:插入、提取与压缩
开发语言·python·excel
Rabitebla19 分钟前
快速排序(QuickSort)完全指南 —— 从原理到工业级优化
c语言·数据结构·c++·算法·github
Dxy123931021619 分钟前
Python 如何反向 `enumerate` 遍历枚举
python
程序员杰哥33 分钟前
软件测试之黑盒测试详解
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例