C ++,printf vs cout性能

我用C ++编写了以下程序,以测量以不同方式打印到默认输出流所花费的时间:

#include <algorithm>
#include <chrono>
#include <iostream>
using namespace std;
using namespace std::chrono;

int main() {
// Get starting timepoint
auto start = high_resolution_clock::now();

for (int i=0;i<100000;i++)
{
    cout << "Hello";
}

// Get ending timepoint
auto stop = high_resolution_clock::now();

// Get duration. Substart timepoints to
// get durarion. To cast it to proper unit
// use duration cast method
auto duration = duration_cast<microseconds>(stop - start);

cout << "Time taken by function: "
     << duration.count() << " microseconds" << endl;

return 0;

}

At the first round I ran it with: cout << "Hello" << endl; and it took 147,570 microseconds.

At the second round I rant it with: cout << "Hello\n"; and took 128,543 microseconds.

Lastly, I ran it with: printf("Hello\n"); and it took 121,223 microseconds.

是什么导致了这种明显的差异?

注意:我取了每项10次测试的平均值。

评论