如何解决与 Python 的 Hashlib 或 Crypto++ 相比,RustsCrypto 的性能较差
出于项目文档目的,我试图比较 Python 的 Hashlib 性能
到使用 Rust 和 C++ 的类似实现。我不太了解 C++ 或 Rust;我的代码有可能没有正确优化。我注意到,与 Crypto++ 和 RustCrypto 相比,使用 Python 的 Hashlib 对 MD5 进行哈希处理的性能更好。下面程序的目的是逐行散列文件内容。下面的代码在 rockyou.txt
上进行了测试; rockyou.txt
是一个包含 14344392 行的单词列表。
Python
在python中我得到了很好的表现;与 RustCrypto 和 Crypto++ 相比的最快性能。
代码
import hashlib
import sys
def HASH_MD5():
"""
Uses MD5 Algorithm to hash files
"""
file = sys.argv[1]
# path,encoding = "utf8",errors = "ignore"
# Ignores any encoding errors in lines
with open(file,encoding="utf8",errors="ignore") as file:
for line in file:
hashlib.md5(bytes(line.strip(),encoding = "utf8")).hexdigest()
#print(hashlib.md5(bytes(line.strip(),encoding = "utf8")).hexdigest())
if __name__ == "__main__":
HASH_MD5()
在 GNU/Linux 上使用 time
和散列 rockyou.txt
我得到以下输出:
real 0m10.489s
user 0m10.473s
sys 0m0.016s
C++
由于我不是 C++ 专家,我决定借用 Crypto++ wiki 的代码。它比 Python 慢,但仍然合理。
代码
#include <crypto++/cryptlib.h>
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include <crypto++/md5.h>
#include <crypto++/files.h>
#include <crypto++/hex.h>
#include <iostream>
//g++ hash.cpp -o b -lcryptopp
int main(int argc,char* argv[]) {
std::ifstream file(argv[1]);
std::string str;
while (std::getline(file,str)) {
byte digest[ CryptoPP::Weak::MD5::DIGESTSIZE ];
CryptoPP::Weak::MD5 hash;
hash.CalculateDigest( digest,(const byte*)str.c_str(),str.length() );
CryptoPP::HexEncoder encoder;
std::string output;
encoder.Attach( new CryptoPP::StringSink( output ) );
encoder.Put( digest,sizeof(digest) );
encoder.MessageEnd();
//std::cout << output << std::endl;
}
}
使用 time
我得到以下输出:
real 0m36.225s
user 0m36.203s
sys 0m0.021s
锈
我对 Rust 几乎一无所知,所以我使用了 RustCrypto Doc 和 this(逐行读取文件)。我知道 Rust 以其性能而闻名;所以我真的不明白为什么要花这么多时间。
代码
use std::env;
use std::fs::File;
use std::io::{BufRead,BufReader};
use std::str;
use md5::{Md5,Digest};
fn main() -> std::io::Result<()> {
let args: Vec<String> = env::args().collect();
let filename = &args[1];
// Open the file in read-only mode (ignoring errors).
let file = File::open(filename)?;
let mut reader = BufReader::new(file);
let mut buf = vec![];
while let Ok(_) = reader.read_until(b'\n',&mut buf) {
if buf.is_empty() {
break;
}
let mut hasher = Md5::new();
hasher.update(&buf);
hasher.finalize();
//println!("Result: {:x}",hash);
buf.clear();
}
Ok(())
}
real 1m28.250s
user 1m28.087s
sys 0m0.108s
结论
为什么上面的 Python 脚本比 Rust 和 C++ 快得多?这是因为 cpython MD5 implementation 吗?还是 Rust 和 C++ 代码写的不好?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。