Skip to content

Instantly share code, notes, and snippets.

@brettwooldridge
Last active May 5, 2017 15:18
Show Gist options
  • Save brettwooldridge/3e470910c1b6b7c13d14c647cfbede70 to your computer and use it in GitHub Desktop.
Save brettwooldridge/3e470910c1b6b7c13d14c647cfbede70 to your computer and use it in GitHub Desktop.
Cheap Java SHA1 Digest speed test
public class DigestTest
{
@Test
public void test() {
String sql = "SELECT count(ZDeviceLite.device_id) FROM device ZDeviceLite";
// This variable is meaningless and only used for benchmarking, to prevent the
// JVM from optimizing away the loops below due to non-use of the returned types.
int hash = 0;
// Warm-up the JIT (default C2 compile threshold is 10000 code path executions)
for (int i = 0; i < 20000; i++) {
hash ^= getSha1Digest().digest(sql.getBytes()).hashCode();
}
// Run cheap timed test of 1000 iterations
long start = System.nanoTime();
for (int i = 0; i < 1000; i++) {
hash ^= getSha1Digest().digest(sql.getBytes()).hashCode();
}
System.out.printf("Hash: %d\nTotal ns: %d\n", hash, (System.nanoTime() - start));
}
private MessageDigest getSha1Digest() {
try {
return MessageDigest.getInstance("SHA-1");
} catch (final NoSuchAlgorithmException e) {
throw new IllegalArgumentException(e);
}
}
}
@brettwooldridge
Copy link
Author

Result: 1000 SHA1 computations in 1714058ns (1.7ms).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment