计算帧率、每秒过多少次

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

输出:

相关推荐
程序员yu8 分钟前
数智码力:Python作用域完全梳理,全局变量局部变量不再混乱
开发语言·python·学习
anew___10 分钟前
舵机——让 Arduino 动起来
c++·stm32·单片机·嵌入式硬件·c
qq_3449205616 分钟前
Qt 鼠标双击QLabel全屏显示图像
c++·qt
北城笑笑19 分钟前
Python Dev 02 & Tkinter webbrowser 实战,手写第一个 Python 桌面 GUI 小工具
人工智能·python·pip
CTA量化套保21 分钟前
搜索“2026年交易工具推荐”时,先问清它要解决什么问题
人工智能·python
Ticnix29 分钟前
答案一个字一个字往外蹦,聊天记录却一条都没存下来
python·agent
Ticnix35 分钟前
"多数新闻站都禁止内嵌"——这句话我信了很久,直到测了 16 个站点
python·agent
f狐0狸x1 小时前
【C++修炼之路】C++继承的探索
c++·继承
虚无的纽扣1 小时前
【C++】C++11的魔法:不止右值引用,C++11赋予的编程神力
c++
贝猫说python1 小时前
阿里云部署qwen 、第5步:阿里云服务器上大模型运行demo.py,固定提示词模板 拼接用户输入,输出符合要求格式结果
python