我发现在Java中计算sha256的速度很慢,例如比Python慢。我编写了两个简单的基准测试,计算1GB零的sha256值。在两种情况下结果都是相同且正确的,但Python用时为5653毫秒,而Java用时为8623毫秒(慢53%)。每次结果都类似,这对我来说是一个重要的区别。
如何使Java中的计算更快?
基准测试:
Java:
如何使Java中的计算更快?
基准测试:
Java:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class BenchmarkSha256 {
public static void main(String... args) throws NoSuchAlgorithmException {
int size = 1024 * 1024;
byte[] bytes = new byte[size];
MessageDigest md = MessageDigest.getInstance("SHA-256");
long startTime = System.nanoTime();
for (int i = 0; i < 1024; i++)
md.update(bytes, 0, size);
long endTime = System.nanoTime();
System.out.println(String.format("%1$064x", new java.math.BigInteger(1, md.digest())));
System.out.println(String.format("%d ms", (endTime - startTime) / 1000000));
}
}
Python:
-->Python:
#!/usr/bin/env python
import hashlib
import time
size = 1024 * 1024
bytes = bytearray(size)
md = hashlib.sha256()
startTime = time.time()
for i in range(0, 1024):
md.update(bytes)
endTime = time.time()
print "%s\n%d ms" % (md.hexdigest(), (endTime - startTime) * 1000)
结果:~> java BenchmarkSha256
49bc20df15e412a64472421e13fe86ff1c5165e18b2afccf160d4dc19fe68a14
8623 ms
~> python BenchmarkSha256.py
49bc20df15e412a64472421e13fe86ff1c5165e18b2afccf160d4dc19fe68a14
5653 ms
Java和Python的版本:
~> java -version
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02, mixed mode)
~> python --version
Python 2.7