重要接口1:获取本线程的 CPU 使用时间 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t);
重要接口2:获取本进程的 CPU 使用时间 clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t);
CPU 使用时间可以理解为代码实际在运算的时间。
#include <cstdlib>
#include <iostream>
#include <ostream>
#include <stdexcept>
#include <stdio.h>
#include <time.h>
#include <thread>
#include <chrono>
#include <vector>
void compute()
{
std::cout << "enter thread: " << std::this_thread::get_id() << std::endl;
const std::chrono::time_point<std::chrono::steady_clock> start =
std::chrono::steady_clock::now();
long a = 0;
for (long i = 0; i < 10000000; i++) {
for (long j = 0; j < 50; j++) {
a += i;
}
}
std::this_thread::sleep_for(std::chrono::seconds(20));
const std::chrono::time_point<std::chrono::steady_clock> end =
std::chrono::steady_clock::now();
auto dt_sec = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();
std::cout << a << " thread " << std::this_thread::get_id() << " run wall time: " << dt_sec << std::endl;
timespec t;
clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t);
std::cout << a << " thread " << std::this_thread::get_id() << " run cpu time: " << t.tv_sec + 1e-9* t.tv_nsec << std::endl;
}
int main()
{
std::cout << "hello world from t1 main!" << std::endl;
const std::chrono::time_point<std::chrono::steady_clock> start =
std::chrono::steady_clock::now();
std::vector<std::thread> v_t;
for (int i = 0; i < 5; i++) {
v_t.push_back(std::thread(compute));
}
for (int i = 0; i < 5; i++) {
v_t[i].join();
}
const std::chrono::time_point<std::chrono::steady_clock> end =
std::chrono::steady_clock::now();
auto dt_sec = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();
std::cout << " main run wall time: " << dt_sec << std::endl;
timespec t;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t);
std::cout << "main run cpu time: " << t.tv_sec + 1e-9* t.tv_nsec << std::endl;
std::cout << "return main" << std::endl;
return 0;
}
输出
```C++
hello world from t1 main!
enter thread: 140318356154112
enter thread: 140318347761408
enter thread: 140318339368704
enter thread: 140318330976000
enter thread: 140318322583296
2499999750000000 thread 140318347761408 run wall time: 20.7371
2499999750000000 thread 140318347761408 run cpu time: 0.736961
2499999750000000 thread 140318356154112 run wall time: 2499999750000000 thread 20.7392
2499999750000000 thread 140318356154112 run cpu time: 0.739221
140318339368704 run wall time: 20.7392
2499999750000000 thread 140318339368704 run cpu time: 0.739155
2499999750000000 thread 140318322583296 run wall time: 20.7393
2499999750000000 thread 140318322583296 run cpu time: 0.739314
2499999750000000 thread 140318330976000 run wall time: 20.7421
2499999750000000 thread 140318330976000 run cpu time: 0.740057
main run wall time: 20.7425
main run cpu time: 3.69665
return main
```