我正在编写一个 Python 命令行实用程序,该实用程序涉及将字符串转换为TextBlob,它是自然语言处理模块的一部分。导入模块非常慢,在我的系统上大约 300 毫秒。为了快速,我创建了一个记忆函数,仅在第一次调用该函数时才将文本转换为 TextBlob。重要的是,如果我在同一文本上运行我的脚本两次,我想避免重新导入 TextBlob 并重新计算 blob,而是从缓存中提取它。这一切都已完成并且工作正常,除了由于某种原因,该功能仍然很慢。事实上,它和以前一样慢。我认为这一定是因为模块被重新导入,即使函数被记忆并且导入语句发生在记忆函数内部。
这里的目标是修复以下代码,以便记忆运行尽可能快,因为不需要重新计算结果。
这是核心代码的最小示例:
@memoize
def make_blob(text):
import textblob
return textblob.TextBlob(text)
if __name__ == '__main__':
make_blob("hello")
这是记忆装饰器:
import os
import shelve
import functools
import inspect
def memoize(f):
"""Cache results of computations on disk in a directory called 'cache'."""
path_of_this_file = os.path.dirname(os.path.realpath(__file__))
cache_dirname = os.path.join(path_of_this_file, "cache")
if not os.path.isdir(cache_dirname):
os.mkdir(cache_dirname)
cache_filename = f.__module__ + "." + f.__name__
cachepath = os.path.join(cache_dirname, cache_filename)
try:
cache = shelve.open(cachepath, protocol=2)
except:
print 'Could not open cache file %s, maybe name collision' % cachepath
cache = None
@functools.wraps(f)
def wrapped(*args, **kwargs):
argdict = {}
# handle instance methods
if hasattr(f, '__self__'):
args = args[1:]
tempargdict = inspect.getcallargs(f, *args, **kwargs)
for k, v in tempargdict.iteritems():
argdict[k] = v
key = str(hash(frozenset(argdict.items())))
try:
return cache[key]
except KeyError:
value = f(*args, **kwargs)
cache[key] = value
cache.sync()
return value
except TypeError:
call_to = f.__module__ + '.' + f.__name__
print ['Warning: could not disk cache call to ',
'%s; it probably has unhashable args'] % (call_to)
return f(*args, **kwargs)
return wrapped
这是一个演示,说明记忆化目前没有节省任何时间:
❯ time python test.py
python test.py 0.33s user 0.11s system 100% cpu 0.437 total
~/Desktop
❯ time python test.py
python test.py 0.33s user 0.11s system 100% cpu 0.436 total
即使函数被正确记忆,这种情况也会发生(放在记忆函数中的打印语句只在脚本第一次运行时给出输出)。
我已将所有内容放在一个 GitHub Gist中,以防万一。