c++ - 如何测量队列中每秒弹出/推送的速率?

标签 c++ multithreading c++11 queue c++-chrono

如果我们假设我们有一个典型的队列实现(带有一个表示节点的链表、一个计数器、一个推送方法和一个弹出方法),什么是衡量到达率和速率的最佳方法新项目离开列表?我是否需要两个单独的线程,一个两个测量每个速率?

欢迎任何伪代码/想法!

(我只是快速写了这个来帮助回答任何问题。为简单起见省略了模板)

class my_queue{
public:
    struct Node{
        Node* next;
        Node* previous;
        int data;
    }

    Node* head;
    Node* tail;
    int queue_size;

    my_queue(){}

    int pop(){
        Node* old_head = head;
        Node* new_head = old_head->previous;
        new_head->next = null;
        head = new_head;
        int data = old_head->data
        delete old_head;
        queue_size--;
        return data;
    }

    void push(int data){
        Node* new_tail = new Node();
        new_node->data = data;
        Node* old_tail = tail;
        old_tail->previous = new_tail;
        new_node->next = old_tail;
        tail = new_tail;
        queue_size++;
    }

    int getSize(){
        return queue_size;
    }
};

最佳答案

看起来很简单:您只需使用两个原子压入/弹出计数器,每个操作都会递增。然后,您使用一个每秒运行一次的线程,记录当前状态(或用它做任何它想做的事)并将计数器重置回 0。

你唯一需要注意的是使用一个计时器来计算在你的函数中花费的时间,以确保你不会偏离 1 秒间隔太远(你也应该复制两个计数器如果您花费大量时间进行处理,请在开始时重置它们)。

关于c++ - 如何测量队列中每秒弹出/推送的速率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21082387/

相关文章:

C++ 11 : decltype behaviour of T and T& derivation [ behaviour distinction between both ]

c++ - TerminateThread() with CloseHandle() on thread which uses only stack plain variables (without alloc) 泄漏内存?

c++ - 选择、std::cin 和 std::getline 不能一起玩

c# - Windows 服务内部轮询的常见做法

c++ - 如何使用 decltype 访问依赖类型?

c++ - 在 C++ 中向枚举添加 "all"选项的好的设计是什么?

c++ - 迁移到 64 位时,内存使用量可能会增长多少?

c++ - 在 Qt 中的线程之间发送对象作为信号参数

c++ - 使用 Mutex 挂起程序

c# - ASP.Net MVC 应用程序中的线程安全全局变量