【问题标题】:Fastest way to search a 12GB file using python使用python搜索12GB文件的最快方法
【发布时间】:2018-01-17 20:07:04
【问题描述】:

我想在一个 12GB 的文本文件中执行 4000 多次搜索。

目前,我正在使用mmap 将文件加载到内存中,效果很好(大约需要 5 秒):

with open('my_file.txt', 'rb') as f:
    m = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ)
    data = m.read(-1)

不幸的是,搜索需要很长时间:

for string_to_search_for in list_of_queries:
    if string_to_search_for in data:
        print "Found a match!"

如何加快搜索速度?

【问题讨论】:

  • 将文本文件加载到数据库中,并使用数据库代替,如果它是一个选项
  • 多线程?
  • 至少尝试使用一次运行所有搜索的正则表达式。目前,您正在多次循环所有数据。而且……嗯……从磁盘中搜索 12 GB 的数据需要一些时间。
  • @MatTheWhale 这可能会破坏页面缓存。这是一个线性搜索,CPython 的 mmap 实现不implement any efficient search algorithm,这意味着问题很可能是 IO 绑定的。

标签: python search mmap


【解决方案1】:

索引文件,然后应用您的搜索。您可以使用 lucene 以更好的方式执行此操作。看看这个帖子Python file indexing and searching

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-31
    • 2013-07-05
    • 1970-01-01
    • 2018-11-29
    • 1970-01-01
    • 2011-08-25
    • 2013-09-04
    • 2010-11-27
    相关资源
    最近更新 更多