Endl vs n

이명신·2022년 12월 7일

STL

목록 보기
2/3
post-thumbnail

endl과 \n은 똑같이 동작하는 것처럼 보이지만 작은 차이가 있습니다.
endl의 경우 새로운 라인을 입력하고 outbuffer를 비우는 기능까지 수행합니다.
때문에 cout << endl; 은 cout << "\n" << flush; 와 같습니다.

코딩테스트와 같이 시간이 중요한 프로그래밍을 할 때는 endl 보다는 \n을 사용하는 것이 좋을수도 있습니다.

예제로 endl , \n, printf 를 사용해
1에서 10000 까지의 for문을 돌 때 걸리는 시간을 측정해 보았습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<iostream>
#include<ctime>
using namespace std;
 
 
int main() {
 
    cout.setf(ios::fixed);
    cout.precision(5);
 
    clock_t start, finish1, finish2, finish3;
    double time1,time2,time3;
    start = clock();
 
    for (int i = 0; i < 10000; i++) {
        cout << i << endl;
    }
 
    finish1 = clock();
    time1 = (double)(finish1 - start);
 
    for (int i = 0; i < 10000; i++) {
        cout << i << "\n";
    }
 
    finish2 = clock();
    time2 = (double)(finish2 - finish1);
 
    for (int i = 0; i < 10000; i++) {
        printf("%d\n",i);
    }
 
    finish3 = clock();
    time3 = (double)(finish3 - finish2);
 
    
    cout << " endl : " << time1 / CLOCKS_PER_SEC << "sec" << endl;
    cout << " \\n : " << time2 / CLOCKS_PER_SEC << "sec" << endl;
    cout << " printf : " << time3 / CLOCKS_PER_SEC << "sec" << endl;
    return 0;
}
 
cs

0개의 댓글