연습 문제 : https://bcp0109.tistory.com/39
입력과 마찬가지로 출력에도 여러가지 방법이 있습니다.
가장 간단한 방법으로는 System.out.print가 있지만 굉장히 느립니다.
보통 알고리즘 답은 많은 출력을 필요로 하지 않지만 여러 개의 테스트케이스에 대해서 출력을 할 때는 시간 초과가 발생할 수 있습니다.
따라서 많은 출력이 필요할 땐 BufferedWriter나 StringBuilder를 사용하는 것을 권장합니다.
이 둘의 특징은 데이터를 모아두었다가 한번에 출력합니다.
BufferedWriter의 경우네는 flush()를 사용하고
StringBuilder의 경우에는 자체적으로 String들을 이어붙인 것이기 때문에 StringBuilder를 출력하면 됩니다.
BufferedWriter를 사용하는 경우에는 입력할 때와 마찬가지로 throws Exception 을 붙여주거나 try 내에서 사용하시면 됩니다.
** 간단한 비교를 위해 10만개의 데이터를 출력해보았습니다.
소요시간은 StringBuilder가 가장 빨랐지만 사실 큰 차이는 없으므로 편한 것을 사용하시면 됩니다.
출력하는 데이터가 적다면 System.out을 사용하여도 괜찮습니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
class Main { | |
public static void main(String[] args) throws Exception { | |
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); | |
StringBuilder sb = new StringBuilder(); | |
long start, end; | |
// System.out.print TEST | |
start = System.currentTimeMillis(); | |
for(int i=0; i<100000; i++) | |
System.out.print(i); | |
end = System.currentTimeMillis(); | |
double sysTime = (end-start) / 1000.0; | |
// bw.write TEST | |
start = System.currentTimeMillis(); | |
for(int i=0; i<100000; i++) | |
bw.write(i + ""); | |
bw.flush(); | |
end = System.currentTimeMillis(); | |
double bwTime = (end-start) / 1000.0; | |
// sb.append TEST | |
start = System.currentTimeMillis(); | |
for(int i=0; i<100000; i++) | |
sb.append(i); | |
System.out.print(sb); | |
end = System.currentTimeMillis(); | |
double sbTime = (end-start) / 1000.0; | |
// Result | |
System.out.println(); | |
System.out.println("sysTime : " + sysTime); | |
System.out.println("bwTime : " + bwTime); | |
System.out.println("sbTime : " + sbTime); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sysTime : 5.411 | |
bwTime : 0.274 | |
sbTime : 0.229 |
'알고리즘 문제 > 공부' 카테고리의 다른 글
2차원 배열 회전 Rotate (Java) (1) | 2020.03.21 |
---|---|
자바 Collections 시간복잡도 (Big-O) (0) | 2019.04.02 |
자바 입력 (Java) (0) | 2019.01.05 |
위상정렬 Topological Sort (Java) (1) | 2018.12.28 |
부분집합 PowerSet (Java) (2) | 2018.12.27 |