计算帧率、每秒过多少次

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

输出:

相关推荐
互联网中的一颗神经元9 分钟前
小白python入门 - 25. SQL 与表设计入门
数据库·python·sql
RSTJ_16251 小时前
PYTHON+AI LLM DAY ONE HUNDRED AND EIGHTEEN
python
开源量化GO2 小时前
近期量化学习路径,交易理解和技术实现要接上
人工智能·python
库克克2 小时前
【C++】set 与multiset
开发语言·c++
Mortalbreeze2 小时前
深入 Linux Socket 编程:端口号、网络字节序与 struct sockaddr 详解
linux·服务器·网络·c++
tkevinjd2 小时前
MiniCode 项目详解7:Memory 记忆系统
大数据·python·搜索引擎·llm·agent
郭老二3 小时前
【Python】Web框架 FastAPI 详解
python·fastapi
DFT计算杂谈3 小时前
交错磁研究进展材料物性与交叉应用
数据库·人工智能·python·opencv·算法
敖行客 Allthinker3 小时前
docker容器安装Python反推镜像步骤(适用于临时调试用)
python·docker·容器
rrrjqy3 小时前
夏普比率与 Beta——Quant-for-Beginners 量化入门Task7
python·金融