我有以下10000000x2矩阵:
0 0
1 1
2 2
.. ..
10000000 10000000
现在我想将这个矩阵保存到int[][]
数组中:
import com.google.common.base.Stopwatch;
static void memory(int size) throws Exception {
System.out.println("Memory");
Stopwatch s = Stopwatch.createStarted();
int[][] l = new int[size][2];
for (int i = 0; i < size; i++) {
l[i][0] = i;
l[i][1] = i;
}
System.out.println("Keeping " + size + " rows in-memory: " + s.stop());
}
public static void main(String[] args) throws Exception {
int size = 10000000;
memory(size);
memory(size);
memory(size);
memory(size);
memory(size);
}
输出:
Keeping 10000000 rows in-memory: 2,945 s
Keeping 10000000 rows in-memory: 408,1 ms
Keeping 10000000 rows in-memory: 761,5 ms
Keeping 10000000 rows in-memory: 543,7 ms
Keeping 10000000 rows in-memory: 408,2 ms
现在我想把这个矩阵保存到磁盘上:
import com.google.common.base.Stopwatch;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
static void file(int size, int fileIndex) throws Exception {
Stopwatch s = Stopwatch.createStarted();
FileOutputStream outputStream = new FileOutputStream("D:\\file" + fileIndex);
BufferedOutputStream buf = new BufferedOutputStream(outputStream);
for (int i = 0; i < size; i++) {
buf.write(bytes(i));
buf.write(bytes(i));
}
buf.close();
outputStream.close();
System.out.println("Writing " + size + " rows: " + s.stop());
}
public static void main(String[] args) throws Exception {
int size = 10000000;
file(size, 1);
file(size, 2);
file(size, 3);
file(size, 4);
file(size, 5);
}
输出:
Writing 10000000 rows: 715,8 ms
Writing 10000000 rows: 636,6 ms
Writing 10000000 rows: 614,6 ms
Writing 10000000 rows: 598,0 ms
Writing 10000000 rows: 611,9 ms
不是应该更快地保存到内存吗?
发布于 2014-07-31 14:41:09
正如评论中所说,你没有衡量任何有用的东西。JVM将写操作缓存在其内存中,然后将其刷新到操作系统,操作系统在最终将其写入磁盘之前将其缓存在其内存中。
但是您只能测量JVM在其自己的内存中缓存它所花费的时间(这是您所能测量的全部时间)。
不管怎么说,你不应该为这样的微优化而烦恼。
发布于 2014-07-31 14:43:51
您的硬盘驱动器和操作系统采用写缓冲,以便您的系统可以在面对多个并发任务(例如,读写磁盘的程序)时继续操作。这可能(有时确实会)在台式机发生电源故障时导致数据丢失。服务器和笔记本电脑也会遇到这个问题(但通常使用称为电池的复杂技术来减少这种可能性)。无论如何,在Linux上你可能不得不使用fsck
,而在Windows上当它发生的时候你可以使用chkdsk
。
https://stackoverflow.com/questions/25052263
复制相似问题