Cro*_*zin 17 java optimization performance input
我有一个文本文件包含1 000 002以下编号中的数字:
123 456
1 2 3 4 5 6 .... 999999 100000
Run Code Online (Sandbox Code Playgroud)
现在我需要读取该数据并将其分配给int变量(前两个数字)和其余所有(1 000 000个数字)到一个数组int[].
这不是一项艰巨的任务,但是 - 它的速度非常慢.
java.util.Scanner: Scanner stdin = new Scanner(new File("./path"));
int n = stdin.nextInt();
int t = stdin.nextInt();
int array[] = new array[n];
for (int i = 0; i < n; i++) {
array[i] = stdin.nextInt();
}
Run Code Online (Sandbox Code Playgroud)
它作为例外工作,但执行大约需要7500毫秒.我需要在几百毫秒内获取该数据.
java.io.BufferedReader:使用BufferedReader.readLine()和String.split()我在大约1700毫秒内得到了相同的结果,但它仍然太多了.
如何在不到1秒的时间内读取该数据量?最终结果应该等于:
int n = 123;
int t = 456;
int array[] = { 1, 2, 3, 4, ..., 999999, 100000 };
Run Code Online (Sandbox Code Playgroud)
StreamTokenizer 解决方案很快(大约需要1400毫秒),但它仍然太慢:
StreamTokenizer st = new StreamTokenizer(new FileReader("./test_grz"));
st.nextToken();
int n = (int) st.nval;
st.nextToken();
int t = (int) st.nval;
int array[] = new int[n];
for (int i = 0; st.nextToken() != StreamTokenizer.TT_EOF; i++) {
array[i] = (int) st.nval;
}
Run Code Online (Sandbox Code Playgroud)
PS.无需验证.我100%确定./test_grz文件中的数据是正确的.
Cro*_*zin 13
感谢您的每一个答案,但我已经找到了符合我标准的方法:
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("./path"));
int n = readInt(bis);
int t = readInt(bis);
int array[] = new int[n];
for (int i = 0; i < n; i++) {
array[i] = readInt(bis);
}
private static int readInt(InputStream in) throws IOException {
int ret = 0;
boolean dig = false;
for (int c = 0; (c = in.read()) != -1; ) {
if (c >= '0' && c <= '9') {
dig = true;
ret = ret * 10 + c - '0';
} else if (dig) break;
}
return ret;
}
Run Code Online (Sandbox Code Playgroud)
读取1毫升整数只需要大约300毫秒!
| 归档时间: |
|
| 查看次数: |
9344 次 |
| 最近记录: |