Skip to content

Instantly share code, notes, and snippets.

@StefanoCappellini
Last active July 23, 2018 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StefanoCappellini/3f3115415ed53add817a66b6a93528ff to your computer and use it in GitHub Desktop.
Save StefanoCappellini/3f3115415ed53add817a66b6a93528ff to your computer and use it in GitHub Desktop.
Python hashlib is twice as fast as Java MessageDigest: see the related post here: http://cppsfn.co/hashlib-vs-messagedigest
public static double comparison(int desiredSize, int bufferSize){
int size = desiredSize / bufferSize * bufferSize;
byte data[] = new byte[size];
new Random().nextBytes(data);
long startTime = 0;
long endTime = 0;
int nRounds = 10;
double elapsed = 0;
for(int round = 0; round < nRounds; round++){
MessageDigest sha = MessageDigest.getInstance("SHA-256");
startTime = System.nanoTime();
for(int i = 0; i < size; i += bufferSize)
sha.update(data, i, bufferSize);
sha.digest();
endTime = System.nanoTime();
elapsed += ((endTime - startTime) / 1000000000.0);
}
return elapsed / nRounds;
}
public static void comparisonAlone(int size){
byte data[] = new byte[size];
new Random().nextBytes(data);
int nRounds = 10;
double total = 0;
for(int round = 0; round < nRounds; round++) {
MessageDigest sha = MessageDigest.getInstance("SHA-256");
long start = System.nanoTime();
sha.digest(data);
long end = System.nanoTime();
total += ((end - start) / 1000000000.);
}
System.out.println(total / nRounds);
}
def comparison(desired_size, buffer_size):
size = (desired_size // buffer_size) * buffer_size
data = np.random.bytes(size)
n_rounds = 10
elapsed = 0
for round in range(n_rounds):
sha = hashlib.sha256()
start = time.time()
for i in range(0, size, buffer_size):
sha.update(data[i:i+buffer_size])
sha.digest()
end = time.time()
elapsed += (start - end)
return elapsed / n_rounds
def comparison_alone(size):
data = np.random.bytes(size)
n_rounds = 10
total = 0
for _ in range(n_rounds):
sha = hashlib.sha256()
start = time.time()
sha.update(data)
sha.digest()
end = time.time()
total += (end - start)
print(total / n_rounds)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment