2014-01-24 3 views
0

표준 출력에 1 백만 줄을 인쇄하고 싶습니다.System.out.println 대 PrintWriter 성능 비교?

System.out.println(result); 

또는

PrintWriter out = new PrintWriter(System.out); 
out.println(result); 
out.flush(); 

더 나은 성능을 얻으려면 (속도 현명), 하나는 내가 사용하고 왜해야하는?

- 편집 - BufferedWriter는 어떨까요?

+5

을하지도, 출력 한 수백만 라인을 게시하지 않습니다 희망 : 여기

비슷한 질문에 대한 링크입니다. 또한 결코하지 않을 물건을 최적화하는 것에 대해 걱정하지 마십시오. –

+1

그것은 생산자 소비자 문제와 같은 버퍼에 달려 있습니다 –

+0

@ user2310289 제안에 감사드립니다. 그러나 나는 실제로 그것을 정확히 할 필요가있는 경우가 있습니다. – noooooooob

답변

0

다른 출력 스트림에서 System.out을 래핑해도 실제로 차이가 없습니다. 그것은 같은 메소드를 호출합니다. 수백만 개의 작은 개체와 콘솔에서 모든 것을 수신하고 보류하고 표시 할 수있는 한계가 있습니다.

또한 간단한 테스트를 쉽게 디자인 할 수 있습니다.

public static void main(String[] args) { 
    System.out.println(); 
    long start = 0L; 

    start = System.currentTimeMillis(); 

    for(int i = 0; i <= 999999; i++) 
     System.out.println(i); 

    long printStreamTime = System.currentTimeMillis() - start; 

    PrintWriter writer = new PrintWriter(System.out); 

    System.gc(); 
    try { 
     Thread.sleep(1000L); 
    } catch(InterruptedException ie) {} 

    start = System.currentTimeMillis(); 

    for(int i = 0; i <= 999999; i++) 
     writer.println(i); 

    long printWriterTime = System.currentTimeMillis() - start; 

    System.out.println(); 

    System.out.println("PrintStream time = " + (printStreamTime/1000.0)); 
    System.out.println("PrintWriter time = " + (printWriterTime/1000.0)); 
} 

둘 다 ~ 49 초입니다. 거의 동일합니다.

속도를 원한다면 파일에 쓰고 그것을여십시오.

+0

답변 해 주셔서 감사합니다. 'auto flush'부울이 어떤 차이를 만들지? http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html#PrintWriter%28java.io.OutputStream,%20boolean%29 – noooooooob