一個操作需要 65 毫秒才能完成。它需要在每秒特定的目標操作中被觸發 ' numOpr ' 次。
我們如何控制以特定速率觸發的操作?
下面是我嘗試過的一個示例,但它似乎并不關心每秒的目標操作。在所有有效的 targetOps 值下,它始終為 ~15ops。
目標環境:gcc5.x,C 11
#include <iostream>
#include <chrono>
#include <thread>
int main()
{
float ops;
//target number of operations
const std::intmax_t targetOPS = 10;
//number of operations
const std::size_t numOpr = 20;
std::chrono::duration<double, std::ratio<1, targetOPS>> timeBetweenOperation;
std::chrono::time_point<std::chrono::steady_clock, decltype(timeBetweenOperation)> tp;
std::chrono::time_point<std::chrono::high_resolution_clock> started = std::chrono::high_resolution_clock::now();
//need to run some operation 10 times at specific intervals
for(size_t i= 0; i<numOpr;i ){
//Some operation taking 65ms
std::this_thread::sleep_for(std::chrono::milliseconds(65));
//delay between each operation if required to reach targetOPS
tp = std::chrono::steady_clock::now() timeBetweenOperation;
std::this_thread::sleep_until(tp);
}
std::chrono::time_point<std::chrono::high_resolution_clock> now = std::chrono::high_resolution_clock::now();
auto dt_us = std::chrono::duration_cast<std::chrono::microseconds> (now - started).count ();
if (dt_us > 0)
{
ops = numOpr * 1000000.0 / dt_us;
}
else
{
ops = 0.0;
}
std::cout<<"Operations per second: "<< ops <<std::endl;
std::cout<<"Target operations per second: ~"<< targetOPS <<std::endl;
}
uj5u.com熱心網友回復:
問題 #1 是您沒有初始化timeBetweenOperation,因此它將以您的 1/N 速率設定為 0 滴答聲。因此,您總是添加 0。您可以通過初始化它來解決這個問題:
std::chrono::duration<double, std::ratio<1, targetOPS>> timeBetweenOperation(1);
問題 #2 是您執行sleep_until. 你一直在睡覺直到now加上間隔,所以你總是會得到 65ms 加上你的 100ms gab,導致每秒 6 次操作。如果您希望每秒執行 N 次操作,則需要now在執行 65ms 操作之前抓取。
for(size_t i= 0; i<numOpr;i ){
//Compute target endpoint
tp = std::chrono::steady_clock::now() timeBetweenOperation;
// Some operation taking 65ms
std::this_thread::sleep_for(std::chrono::milliseconds(65));
std::this_thread::sleep_until(tp);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/440816.html
