我正在编写一个Python脚本(使用python3.2),在某个时候,它需要为字典中的每个键遍历大约800.000行的文件。钥匙的数量大约是15万。文件中的行是以下格式的词典:
{'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。这将导致120.000.000.000调用eval,这需要很长时间。因此,我正在寻找一种方法来优化这一点。在
欢迎您提出所有可能的优化建议。每一点都可能有影响,但我主要对eval和我读取文件的方式感兴趣。自动取款机。我在想eval可能会执行得更快一些,但是我不能让JSON读取格式,使用split还不是很好。 另外,我从文件中读取的方式可能会得到优化。我在下面的代码中尝试了该方法,并使用了“with”(速度慢得多,但占用的内存较少)。我还尝试使用map读取内存中的文件:
^{pr2}$但这也不起作用。在
不管怎样,下面的脚本是最重的部分。它在多个进程中运行:
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]]}]]}
在真实数据的一个子集上,在我运行pstats的文件中有562个键和2232行,按时间降序排序(这只是顶部):
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)
从这看来,这确实是埃瓦尔占用时间。在
编辑:按照建议,我尝试了文字评估。事实上,我发现这是在试图找到一个解决方案,但我认为它会和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}
这是个好消息,但更好的是我使用pickle的第二种方法。现在我得到:
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}
当我有时间的时候,我会尝试将这种方法应用到全套。在
有什么建议吗?在
谨致问候, 卡斯帕
你应该试试^{} ,它是为工作而设计的,可能会更快。在
eval()
速度慢,不安全,通常是个坏主意。如果你认为你需要它,看看周围,我向你保证你不会99.99%的时间。在另一个注意事项是:
应该是:
^{pr2}$文件是迭代器,所以使用},因为它已经过更新以支持后者的额外功能)。在
readlines()
只会降低程序的内存效率。使用with
可确保文件在完成后正确关闭(就像在3.x中一样,您可以使用open()
而不是{除此之外,据我所知,数据的每一行都应该是有效的JSON,因此
json
模块也应该可以工作。在相关问题 更多 >
编程相关推荐