以这段代码为例:
def get_hash(path, hash_type='md5'):
func = getattr(hashlib, hash_type)()
f = os.open(path, (os.O_RDWR | os.O_BINARY))
for block in iter(lambda: os.read(f, 1024*func.block_size), b''):
func.update(block)
os.close(f)
return func.hexdigest()
此函数返回任何文件的 md5sum。假设我有一个包含 30 多个文件的目录,并且我想对每个文件运行散列函数:
def hasher(path=some_path):
for root, dirs, files in os.walk(path, topdown=False):
for name in files:
path = os.path.join(root, name)
yield get_hash(path)
@some_timer_decorator
... some testing function here ...
test1 took 4.684999942779541 seconds.
现在,如您所见,手头的情况让我有机会“利用”该hasher
功能并添加多处理:
def hasher_parallel(path=PATH):
p = multiprocessing.Pool(3)
for root, dirs, files in os.walk(path, topdown=False):
for name in files:
full_name = os.path.join(root, name)
yield p.apply_async(get_hash, (full_name,)).get()
@some_timer_decorator
... some other testing function here ...
test2 took 4.781000137329102 seconds.
输出是相同的。我期待并行版本更快,因为大多数文件都小于<20MB,并且hasher
函数计算这些总和非常快(通常,对于那种大小的文件)。我的实现有问题吗?如果没有问题,是否有更快的方法来解决同样的问题?
这是我用来测量执行时间的装饰器函数:
def hasher_time(f):
def f_timer(*args, **kwargs):
start = time.time()
result = f(*args, **kwargs)
end = time.time()
print(f.__name__, 'took', end - start, 'seconds')
return result
return f_timer
#