"I want to write a program that consumes 5 seconds of CPU time, where the time spent off the CPU due to IO, context switches, etc., is not counted towards this 5-second time quota.
Currently, I've used the std::chrono approach, but it obviously doesn't meet the requirements, as when I call sleep to yield the CPU, this one second is also counted towards the program's execution time. Resulting in a low task-clock in perf.
#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;
}
In this test, it's possible to manually exclude the time spent in sleep by tracking it, but for involuntary CPU yields (such as CPU time-sharing that occurs when there are a large number of threads), it's not possible to account for this off-CPU time through code.