In [8]: %paste
PRIME = 16777619
UINT32_MAX = 4294967295 # (2 ** 32) - 1
def fnv1a_32_global(string):
hashval = 2166136261
for character in string:
hashval ^= ord(character)
hashval = (hashval * PRIME) & UINT32_MAX
return hashval
In [9]: %timeit fnv1a_32_global(mystr)
1000000 loops, best of 3: 990 ns per loop
In [6]: %paste
def fnv1a_32_local(string):
hashval = 2166136261
PRIME = 16777619
UINT32_MAX = 4294967295 # (2 ** 32) - 1
for character in string:
hashval ^= ord(character)
hashval = (hashval * PRIME) & UINT32_MAX
return hashval
In [7]: %timeit fnv1a_32_local(mystr)
1000000 loops, best of 3: 967 ns per loop
我正在尝试确认(并理解为什么)在每个函数调用上初始化本地var并且访问它比一次初始化全局var并访问它更快。
此结果在多次测试尝试中保持一致。
Additinal问题:这个代码可以更快地制作(我尝试使用c-library pyfasthash。它比上面的实现更慢)