粗略估计Python进行字符串比较所需的时间

2024-09-27 23:21:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,称之为段落,包含50-100个单词,用空格隔开。 我有一个5500个字符串的数组,大约3-5个字符长。 我要做的是检查段落中的每个单词,看看这些单词是否也包含在5500个字符串的数组中。在

有人粗略估计一下在Python中进行一次重温所需的时间吗? 我想对照数组检查段落中的每个单词

我想我写代码的过程不会太长。在

如果这个问题太懒了。。。如何在这样一个简单的字符串示例中找到Python的计算时间?在


Tags: 字符串代码示例过程时间数组单词段落
2条回答

如果使用list,请先对其排序并使用二进制搜索。在

但使用字典可能会更好;)

import time

def timeo(fun, n=1000): 
    def void(  ): pass 
    start = time.clock(  ) 
    for i in range(n): void(  ) 
    stend = time.clock(  ) 
    overhead = stend - start 
    start = time.clock(  ) 
    for i in range(n): fun(  ) 
    stend = time.clock(  ) 
    fulltime = stend-start 
    return fun.__name__, fulltime-overhead 

for f in solution1, solution2, solution3:
    print "%s: %.2f" % timeo(f)

我会把你的5500个字符串数组转换成一个集合,只使用集合交集。在

>>> paragraph = "five hundred to one hundred words separated by spaces"
>>> array_of_strings = set(['hundred', 'spaces', ])  # make a set..

>>> print set(paragraph.split()).intersection(array_of_strings)
set(['hundred', 'spaces'])

下面是你计时的方法。在

阅读timeit模块。这是另一个教程:http://diveintopython.net/performance_tuning/timeit.html

^{pr2}$

相关问题 更多 >

    热门问题