0

我正在测量 printf 和 cout 用于给定输出(数字)的时间量,并想知道是否有更好的方法来测量 C++ 中的纳秒精度(或者此代码是否需要改进)。

int rand1 = rand();
auto start = std::chrono::high_resolution_clock::now();
printf("%d", rand1);
auto finish = std::chrono::high_resolution_clock::now();
double secondsPrintf = (double)std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count();
auto start1 = std::chrono::high_resolution_clock::now();
std::cout << rand1;
auto finish1 = std::chrono::high_resolution_clock::now();
std::cout << endl; // measuring performance of printing the number, no need for endl (drastically lowers performance)
double secondsCout = (double)std::chrono::duration_cast<std::chrono::nanoseconds>(finish1-start1).count();

我听说 chrono 的 now() 函数非常精确,但是有没有更好的方法(或更高效、更快等)来执行这些操作?

4

0 回答 0