hashlib md5 is slow
I need md5 checksums in part of a program. I created a small test script just to see how this works. The script is almost twice as slow as calling md5sum directly. Anyway I can tweak this or should I just use subprocess to call md5sum?
#!/usr/bin/python
import sys
import hashlib
filename=sys.argv[1]
class md5_checksum(object):
def __init___(self):
pass
def create_checksum(self, x):
self.x=x
self.x=hashlib.md5(open(self.x,'rb').read()).hexdigest()
def return_checksum(self):
return self.x
m=md5_checksum()
m.create_checksum(filename)
print "The checksum for file '" + filename + "' is", m.return_checksum() + '.'
13 comments · 85% upvoted · other discussions
You are reading the entire contents of
self.xinto memory at one time. How big are these files? What happens if you instead stream the contents in a block at a time?http://stackoverflow.com/a/3431838/3140
From a code review standpoint, it confuses me when you use
self.xto temporarily store the filename and then the resulting hash. Rename the argument fromxtofilename, and renameself.xto something more descriptive.LarryPete 6 points · Jan 2016 · Advanced Python 3
I wanted to answer the same way, but you beat me to it.
But for comparison, my results were:
So, pretty much no difference. The python version was even slightly faster (even if I retry).
pinano 1 points · Jan 2016
Is
test.pythe block-at-a-time version or OP's.read()version?Also, does the performance differ in python2 vs python3?
LarryPete 2 points · Jan 2016 · Advanced Python 3
No, it's block-at-a-time.
Loading a 10GB file into my memory would probably kill my PC anyway :-)
Edit: And no, no significant difference between python2 and 3.
StorageNinja [OP] 2 points · Jan 2016
thx for the review, I could not agree more. It is already fixed up.
I will try the block at a time next.
[deleted] 1 points · Jan 2016
[deleted]
pinano 1 points · Jan 2016
First, interleaving I/O and computation allows the computer to maximize its utilization of both. On the default Python implementation,
file.read(N)calls down to the C stdlib functionfread, which is very likely to have its own read-ahead buffer and filesystem cache.Also, these are 100MB-20GB files. If /u/StorageNinja has less than that much free memory, then the program is guaranteed to hit swap.