There was a topic here that the Java Scanner was very slow, so I measured how slow it was, so I will report it briefly.
Comparison of speeds in Python, Java, C ++
number of data=One million | Execution time |
---|---|
Java Scanner | 714 msec |
Own Scanner | 24 msec |
magnification | 29.75 |
Compared to your own simple Scanner, Java Scanner takes about 30 times longer. It seems better not to use Sanner in competitive programming.
Below is the code used for comparison.
import java.util.*;
import java.io.*;
import java.util.stream.*;
public class ScannerTest {
public static void main(String[] args) {
long t0 = System.currentTimeMillis();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] d = new int[n];
for (int i = 0; i < n; i++) {
d[i] = sc.nextInt();
}
long t1 = System.currentTimeMillis();
System.out.println("n = " + n );
System.out.println((t1-t0) + " msec");
int sum = IntStream.of(d).sum();
System.out.println("sum = " + sum);
}
}
import java.util.*;
import java.io.*;
import java.util.stream.*;
public class ScannerTest3 {
static class MyScanner {
byte[] bytes;
int pos = 0;
int len;
InputStream inputStream;
MyScanner(InputStream is){
try{
inputStream = is;
bytes = new byte[1024];
len = Math.max(0,inputStream.read(bytes));
pos = 0;
return;
}catch(Exception e){
e.printStackTrace();
}
}
private byte getNextByte() throws IOException {//throws ArrayIndexOutOfBoundsException
if( pos >= len ){
len = Math.max(0,inputStream.read(bytes));
pos = 0;
}
byte result = bytes[pos++];
return result;
}
int nextInt() throws IOException {
int result = 0;
byte v;
while(true){
v = getNextByte();
if( v != ' ' && v != '\n' && v != '\r'){
break;
}
}
while(true){
if( v == ' ' || v == '\n' || v == '\r' ){
break;
}
result *= 10;
result += (int)v - (int)'0';
v = getNextByte();
}
return result;
}
}
public static void main(String[] args) throws Exception{
long t0 = System.currentTimeMillis();
MyScanner sc = new MyScanner(System.in);
int n = sc.nextInt();
int[] d = new int[n];
for (int i = 0; i < n; i++) {
d[i] = sc.nextInt();
}
long t1 = System.currentTimeMillis();
System.out.println("n = " + n );
System.out.println((t1-t0) + " msec");
int sum = IntStream.of(d).sum();
System.out.println("sum = " + sum);
}
}
Recommended Posts