我正在编写一个程序,并尝试计算给定代码块运行时经过的秒数.之后我想打印在几秒钟内运行代码块所花费的总时间.我写的是:
time_t start = time(0);
// block of code
double seconds_since_start = difftime(time(0), start);
printf("seconds since start: %2.60f\n", seconds_since_start);
Run Code Online (Sandbox Code Playgroud)
我printf()打印到60小数精度,所有时间仍然是0.000000 ...
我的时间功能有错误吗?我发现很难相信我要求的任务时间不会占用60小数精度的任何时间.
您可以使用C++ 11中提供的日期和时间实用程序:
#include <chrono>
#include <iostream>
#include <thread>
int main()
{
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(std::chrono::seconds(5));
auto end = std::chrono::high_resolution_clock::now();
auto difference = std::chrono::duration_cast<std::chrono::seconds>(end - start).count();
std::cout << "Seconds since start: " << difference;
}
Run Code Online (Sandbox Code Playgroud)
返回值time是一个整数秒.施放到一个double将不会带回已经丢失的小数秒.
您需要更精确的时钟功能,例如gettimeofday(如果您需要挂钟时间)或times(如果您需要CPU时间).
在Windows中,有timeGetTime,QueryPerformanceCounter(这Castiblanco证明),或GetSystemTimeAsFileTime.
C++终于得到了一些标准的高分辨率时钟函数和C++ 11的<chrono>标题,Chris在评论中提出了这一点.