计算帧率、每秒过多少次

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

输出:

相关推荐
Direction_Wind4 分钟前
抖音视频下载,直播间监控,直播间发言采集,最新加密算法
python·node.js
DYS_房东的猫5 分钟前
《 C++ 零基础入门教程》第5章:智能指针与 RAII —— 让内存管理自动化
开发语言·c++·自动化
%xiao Q8 分钟前
信息学奥赛一本通(部分题解)
c语言·c++·算法
w-w0w-w9 分钟前
C++ list简单模拟实现
数据结构·c++
旦莫11 分钟前
使用OCR加持的APP自动化测试
python·测试开发·自动化·ocr·pytest·ai测试
枫叶丹412 分钟前
【Qt开发】Qt系统(六)-> Qt 线程安全
c语言·开发语言·数据库·c++·qt·安全
信奥胡老师12 分钟前
P14917 [GESP202512 五级] 数字移动
开发语言·数据结构·c++·学习·算法
天若有情67313 分钟前
用 Python 爬取电商商品数据:从入门到反爬破解
开发语言·python
txinyu的博客14 分钟前
结合STL,服务器项目解析vetcor map unordered_map
开发语言·c++
Nsequence15 分钟前
第四篇 STL-list
c++·算法·stl