以下完整程序显示了如何使用 C++11 中添加的 std::chrono 工具来完成此操作:
#include <iostream>
#include <chrono>
#include <thread>
int main(int argc, char *argv[]) {
// Check args.
if (argc != 2) {
std::cerr << "Usage: testprog <sleepTime>" << std::endl;
return 1;
}
// Create a millisecond sleep time from argument.
auto sleepTime = strtoul(argv[1], nullptr, 10);
sleepTime = sleepTime * 1234 + 1000;
std::cout << "Given '" << argv[1] <<
"', should sleep for about " << sleepTime <<
"ms ... " << std::flush;
// Get the start time, then wait for a bit.
auto startTime(std::chrono::high_resolution_clock::now());
std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));
// Get end time, work out and print duration.
auto endTime(std::chrono::high_resolution_clock::now());
auto duration(std::chrono::duration_cast<std::chrono::milliseconds>
(endTime - startTime));
std::cout << "that took " << duration.count() << "ms." << std::endl;
}
使用以下bash 测试命令运行它:
for i in {0..10} ; do ./testprog $i ; done
为您提供您期望的结果:
Given '0', should sleep for about 1000ms ... that took 1000ms.
Given '1', should sleep for about 2234ms ... that took 2235ms.
Given '2', should sleep for about 3468ms ... that took 3469ms.
Given '3', should sleep for about 4702ms ... that took 4703ms.
Given '4', should sleep for about 5936ms ... that took 5937ms.
Given '5', should sleep for about 7170ms ... that took 7170ms.
Given '6', should sleep for about 8404ms ... that took 8404ms.
Given '7', should sleep for about 9638ms ... that took 9638ms.
Given '8', should sleep for about 10872ms ... that took 10872ms.
Given '9', should sleep for about 12106ms ... that took 12106ms.
Given '10', should sleep for about 13340ms ... that took 13340ms.
该代码中的 important 行实际上只是获取开始和结束时间点然后计算出它们之间的持续时间的行。它们可以归结为:
#include <chrono>
auto startTime(std::chrono::high_resolution_clock::now());
// Do whatever you want to time.
auto endTime(std::chrono::high_resolution_clock::now());
auto duration(std::chrono::duration_cast<std::chrono::milliseconds>
(endTime - startTime));
auto elapsedMs = duration.count();