【发布时间】:2018-09-20 12:06:37
【问题描述】:
我使用 Boost 计算 SHA1 哈希,然后将朗姆酒时间与 Linux 命令 md5sum 和 sha1sum 进行比较。文件大小为28G。 md5sum 和 sha1sum 都是 8.4 版。
这就是我使用 Boost 计算 SHA1 的方式:
void Sha1_Key(const std::string& inputfilename_, uint32_t* inputfile_sha1)
{
std::string sha1_key_string;
uint32_t local_sha1[5];
for (uint32_t i = 0; i < 5; ++i)
{
inputfile_sha1[i] = local_sha1[i] = 0;
}
std::ifstream ifs(inputfilename_,std::ios::binary);
boost::uuids::detail::sha1 sha1;
std::stringstream sha1_key;
char buf[128*1024];
clock_t begin = clock();
while(ifs.good()) {
ifs.read(buf,sizeof(buf));
sha1.process_bytes(buf,ifs.gcount());
}
ifs.close();
sha1.get_digest(local_sha1);
for(std::size_t i=0; i<sizeof(local_sha1)/sizeof(local_sha1[0]); ++i) {
sha1_key<<std::hex<<local_sha1[i];
inputfile_sha1[i] = local_sha1[i];
}
sha1_key_string = sha1_key.str();
clock_t end = clock();
std::cout << "run time for Boost SHA1: " << double(end - begin)/CLOCKS_PER_SEC << " sec";
}
这是运行时间比较:
提升 SHA1:170 秒
md5sum: 54.719s
sha1sum: 81.795s
sha1sum 的复杂度比md5sum 高,所以sha1sum 多花50% 的时间。但是 Boost SHA1 方法的运行时间是 Linux sha1sum 的两倍。为什么?
有什么可以改进我的代码的吗?或者对使用其他哈希方法有什么建议?
【问题讨论】:
-
您是否在打开优化的情况下进行编译?
-
重叠 I/O 和计算。在同一个线程中交替执行不是很有效。
-
@Ext3h 这是用于计算 SHA1 的函数,因此它应该包括所有重叠和开销。否则我只需要在我的代码中调用 md5sum。
-
也许 sha1sum 只是包含比 Boost 更优化的 SHA1 实现。
-
+1 让
read循环正确,gcount(我认为:))