printf, puts, cout 문자열 출력 수행시간 비교

문득 저 출력 함수들 간에 얼마만큼의 성능차가 있을지 궁금해서 짜보았다.

코드는 아래와 같다.
같은 문자열을 100번씩 출력함.

| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 | #include "stdafx.h" // iostream, cstdio, chrono, Windows.h int main(){    using std::cout;    using std::endl;    using std::ios_base;    using std::chrono::system_clock;    using std::chrono::duration_cast;    using std::chrono::nanoseconds;     char str[] = "Hello";    system_clock::time_point start;    system_clock::time_point end;            start= system_clock::now();    for (int n = 0; n < 100; n++)        printf("%s",str);    end = system_clock::now();    auto printf_time = duration_cast(end - start).count();     start = system_clock::now();    for (int n = 0; n < 100; n++)        puts(str);    end = system_clock::now();    auto puts_time = duration_cast(end - start).count();     start = system_clock::now();    for (int n = 0; n < 100; n++)        std::cout << str;    end = system_clock::now();    auto cout_time = duration_cast(end - start).count();     ios_base::sync_with_stdio(false);    start = system_clock::now();    for (int n = 0; n < 100; n++)        std::cout << str;    end = system_clock::now();    auto nosync_time = duration_cast(end - start).count();     system("cls");     std::cout << "printf : " << printf_time << "nanoseconds" << endl        << "puts : " << puts_time << "nanoseconds" << endl        << "cout : " << cout_time << "nanoseconds" << endl        << "no sync cout : " << nosync_time << "nanoseconds" << endl;        return 0;}Colored by Color Scripter | cs |



컴파일러는 VS2017 사용

결과

약간 의외의 결과가 나왔다.

일단 printf는 2000만 나노초로 가장 수행시간이 가장 빠르다.

puts는 그래도 노멀 c기능이니까 빠를거라 생각했는데 3억 나노초로 가장 늦다. 개행처리가 조금 시간을 먹긴 하겠지만 간극이 심하게 큰 걸 보면 플러시기능까지 내장되어 있어서 느린 게 아닌가 싶다. 레퍼런스를 뒤져봐야겠다.

cout는 당연히 printf보다 늦게 1억 나노초가 나왔다.

stdio와의 싱크를 끊으면 cout도 빨라진다길래 돌려봤는데 그래도 느리다.. 7500만 나노초.
역시 성능 뽑기에는 그냥 printf가 최고인것같다.