“我想编写一个消耗 5 秒 CPU 时间的程序,其中由于 IO、上下文切换等而消耗 CPU 的时间不计入这 5 秒的时间配额。
目前我已经使用了
std::chrono
的方式,但是显然不符合要求,因为当我调用sleep
让出CPU时,这一秒也被计入了程序的执行时间。导致性能较低task-clock
。
#include <chrono>
#include <thread>
#include <iostream>
#include <cmath>
int main() {
auto start = std::chrono::high_resolution_clock::now();
auto end = start;
while (true) {
end = std::chrono::high_resolution_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(end - start);
if (elapsed.count() >= 5) {
break;
}
volatile double d = 0;
for (int n = 0; n < 10000; ++n) {
d += std::sqrt(n);
}
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "wake" << std::endl;
}
std::cout << "CPU time used: 5 seconds" << std::endl;
return 0;
}
在此测试中,可以通过跟踪来手动排除睡眠所花费的时间,但对于非自愿的 CPU 收益(例如,当存在大量线程时发生的 CPU 分时),无法考虑这一点通过代码关闭 CPU 时间。
#include<iostream>
#include<time.h>
#include<cmath>
using namespace std;
int main(){
clock_t start=clock();
volatile double d=0;
while((clock()-start)/CLOCKS_PER_SEC<5){
for(int n=0;n<10000;++n){
d+=sqrt(n);
}
}
cout<<"CPU time used: 5 seconds"<<endl;
return 0;
}