使用eval优化Python读取大文件

时间:2013-03-14 13:01:24

标签: python file optimization eval

我正在编写一个Python脚本(使用Python 3.2),在某些时候需要通过一个大约800.000行的文件来为字典中的每个键。键的数量约为150.000。文件中的行是以下格式的字典:

{'url': 'http://address.com/document/42/1998', 'referrer': 'http://address.com/search?&q=query1', 'session': '1', 'rank': 2, 'time': 1338447254}
{'url': 'http://address.com/document/55/17', 'referrer': 'http://address.com/search&q=query2', 'session': '1', 'rank': 2, 'time': 13384462462}

对于此文件中的每一行,我需要进行一些计算并存储结果。为了能够阅读字典并对其进行处理,我使用了eval。这将导致对eval的120.000.000.000次调用,这需要很长时间。因此,我正在寻找一种优化方法。

欢迎您提供所有可能的优化建议。每一点都可能产生影响,但我主要对eval以及我读取文件的方式感兴趣。自动取款机。我认为eval可能执行得更快的其他一些方法,但是我不能让JSON读取格式并使用split还没有结果。 我也可以优化从文件中读取的方式。我已经尝试过以下代码中的方法,以及“with”(速度慢得多,但消耗的内存更少)。我还尝试使用map:

在内存中读取文件
f_chunk = map(eval, codecs.open(chunk_file, "r", encoding="utf-8").readlines())

但这也不起作用。

无论如何,脚本的以下部分是沉重的。它在多个过程中运行:

def mine(id, tmp_sessions, chunk_file, work_q, result_q, init_qsize):
    #f_chunk = map(eval, codecs.open(chunk_file, "r", encoding="utf-8").readlines())
    f_chunk = codecs.open(chunk_file, "r", encoding="utf-8").readlines()

    while True:
        try:

            k = work_q.get()
            if k == 'STOP':

                work_q.task_done()
                break # reached end of queue

        except Queue.Empty:
            break

        #with codecs.open(chunk_file, "r", encoding="utf-8") as f_chunk:
        for line in f_chunk:
            #try:
            jlog_nest = dict()
            jlog_nest = eval(line)

            #jlog_nest = json.loads(line)
            #jlog_nest = line
            #jlog_nest = defaultdict(line)


            if jlog_nest["session"] == k: # If session is the same
                query_nest = prepare_test_cases_lib.extract_query(jlog_nest["referrer"])

                for q in tmp_sessions[k]:

                    if q[0] == query_nest:
                        url = jlog_nest["url"]
                        rank = jlog_nest["rank"]
                        doc_id = prepare_test_cases_lib.extract_document_id(url)

                        # Increase number of hits on that document, and save its rank
                        if doc_id in q[1]:
                            q[1][doc_id][0] += 1
                            q[1][doc_id][1].append(rank)
                        else:
                            q[1][doc_id] = [1, [rank]]
            #except:
            #    print ("error",k)

        result_q.put((k, tmp_sessions[k]))
        work_q.task_done()

如果在运行上述代码之前有助于理解tmp_session可能会发生什么:

tmp_sessions: {'39': [['q7', {}], ['q2', {}]], '40': [['q2', {}]]}

之后:

tmp_sessions: {'39': [['q7', {}], ['q2', {'133378': [1, [2]]}]], '40': [['q2', {'133378': [1, [2]]}]]}

在真实数据的一个子集上,文件中有562个键和2232行我运行pstats,按时间降序排序(这只是顶部):

1284892 function calls in 76.810 seconds

Ordered by: cumulative time

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     8    0.000    0.000   77.985    9.748 {built-in method exec}
     8    1.607    0.201   77.978    9.747 prepare_hard_test_cases.py:29(mine)
1254384   75.051    0.000   76.220    0.000 {built-in method eval}
   562    0.008    0.000    0.050    0.000 queues.py:99(put)
     8    0.000    0.000    0.029    0.004 codecs.py:685(readlines)

从这看起来它似乎确实需要花费时间。

编辑:正如我所建议的那样,我尝试使用literal_eval。我实际上发现这试图找到一个解决方案,但认为它将与eval相同。我跑了。它确实产生了相同的结果,但运行时间非常糟糕:

 50205868 function calls (37662028 primitive calls) in 121.494 seconds

 Ordered by: cumulative time

 ncalls  tottime  percall  cumtime  percall filename:lineno(function)
      8    0.001    0.000  121.494   15.187 {built-in method exec}
      8    0.008    0.001  121.493   15.187 <string>:1(<module>)
      8    4.935    0.617  121.485   15.186 prepare_hard_test_cases.py:29(mine)
1254384    5.088    0.000  116.425    0.000 ast.py:39(literal_eval)
1254384    1.098    0.000   71.432    0.000 ast.py:31(parse)
1254384   70.333    0.000   70.333    0.000 {built-in method compile}
13798224/1254384   22.996    0.000   39.336    0.000 ast.py:51(_convert)
7526304    8.539    0.000   23.042    0.000 ast.py:63(<genexpr>)
25087680    8.371    0.000    8.371    0.000 {built-in method isinstance}
    8    0.001    0.000    0.047    0.006 codecs.py:685(readlines)

编辑2:我现在尝试了两种新方法。第一个是通过从每一行手动提取键和值,构建一个字典来处理。这在我的测试集上运行得快一点:

51460252 function calls in 45.207 seconds

 Ordered by: cumulative time

 ncalls  tottime  percall  cumtime  percall filename:lineno(function)
      8    0.001    0.000   45.207    5.651 {built-in method exec}
      8    0.003    0.000   45.207    5.651 <string>:1(<module>)
      8    1.701    0.213   45.203    5.650 prepare_hard_test_cases.py:68(mine)
1254384    5.725    0.000   43.391    0.000 prepare_hard_test_cases.py:36(extractDict)
6271920   23.433    0.000   37.665    0.000 prepare_hard_test_cases.py:20(extractKeyValue)
18819074   11.308    0.000   11.308    0.000 {method 'find' of 'str' objects}
25092651    2.927    0.000    2.927    0.000 {built-in method len}

这是个好消息,但更好的是我使用泡菜的第二种方法。现在我明白了:

30091 function calls in 5.285 seconds

Ordered by: cumulative time

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     8    0.000    0.000    5.285    0.661 {built-in method exec}
     8    0.003    0.000    5.285    0.661 <string>:1(<module>)
     8    0.173    0.022    5.281    0.660 prepare_hard_test_cases.py:68(mine)
   570    0.001    0.000    5.057    0.009 queues.py:113(get)
  2281    3.925    0.002    3.925    0.002 {method 'acquire' of '_multiprocessing.SemLock' objects}
   570    1.133    0.002    1.133    0.002 {method 'recv' of '_multiprocessing.PipeConnection' objects}
     8    0.029    0.004    0.029    0.004 {built-in method load}

当我得到时间时,我将尝试将此方法应用于整套。

有什么建议吗?

祝你好运, 卡斯帕

1 个答案:

答案 0 :(得分:2)

你应该试试ast.literal_eval(),它是专为工作而设计的,并且可能会更快。

eval()缓慢,不安全,通常是个坏主意。如果您认为自己需要它,请浏览一下,我保证您没有99.99%的时间。

另外注意:

f_chunk = codecs.open(chunk_file, "r", encoding="utf-8").readlines()
...

应该是:

with open(chunk_file, "r", encoding="utf-8") as f_chunk:
    ...

文件是迭代器,因此使用readlines()只会降低程序的内存效率。使用with可确保您的文件在完成后正常关闭(因为您在3.x中,因为它已更新以支持其他功能,因此您可以使用open()代替codecs.open()后者)。

除此之外,据我所知,您的数据的每一行都应该是有效的JSON,因此json模块也应该有用。

相关问题