比较两个文件,或者为什么java中的代码比C++快?
为什么java中的代码比C++快? 我需要逐字节比较两个文件。 例如,当比较两个文件大小时,650MB需要40秒到C++,10秒为java。p>C++代码:
//bufferSize = 8mb
std::ifstream lFile(lFilePath.c_str(), std::ios::in | std::ios::binary);
std::ifstream rFile(rFilePath.c_str(), std::ios::in | std::ios::binary);
std::streamsize lReadBytesCount = 0;
std::streamsize rReadBytesCount = 0;
do {
lFile.read(p_lBuffer, *bufferSize);
rFile.read(p_rBuffer, *bufferSize);
lReadBytesCount = lFile.gcount();
rReadBytesCount = rFile.gcount();
if (lReadBytesCount != rReadBytesCount ||
std::memcmp(p_lBuffer, p_rBuffer, lReadBytesCount) != 0)
{
return false;
}
} while (lFile.good() || rFile.good());
return true;
和Java代码:
InputStream is1 = new BufferedInputStream(new FileInputStream(f1));
InputStream is2 = new BufferedInputStream(new FileInputStream(f2));
byte[] buffer1 = new byte[64];
byte[] buffer2 = new byte[64];
int readBytesCount1 = 0, readBytesCount2 = 0;
while (
(readBytesCount1 = is1.read(buffer1)) != -1 &&
(readBytesCount2 = is2.read(buffer2)) != -1
) {
if (Arrays.equals(buffer1, buffer2) && readBytesCount1 == readBytesCount2)
countItr++;
else {
result = false
break;
}
}
# 1 楼答案
数据块位于系统文件缓存中,第二次没有磁盘访问来检索文件。为了获得比较的结果,用C++和java程序多次运行测试。p>
在你的代码中,你有
这与你一开始的评论相矛盾
所以,除非你展示真实的完整的代码,否则任何人的猜测都是正确的
吃我自己的狗粮
# 2 楼答案
虽然缓冲区大小的答案非常好,而且可能非常重要,但问题的另一个可能来源是使用
iostream
库。我一般不会用那个图书馆做这种工作。例如,这可能导致的一个问题是额外的复制,因为iostream
为您提供了缓冲。我将使用原始的read
和write
调用例如,在Linux C++11平台上,我会这样做:
# 3 楼答案
此外,如果文件相同,则可能还有其他原因造成差异。考虑分配8 MB数据(甚至跨越多个页面)所需的时间,而不是简单分配64个字节所需的时间。由于您是按顺序读取的,因此开销实际上在内存方面