首页 文章

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

提问于
浏览
0

我有一个字符串,称之为段落,其中包含由空格分隔的约50-100个单词 . 我有一个5500个字符串的数组,大约3-5个字符长 . 我想要做的是检查段落中的每个单词,看看我的5500字符串数组中是否还包含任何单词 .

有没有人粗略估计在Python中进行一次性的时间?我想检查段落中对阵列的每个单词

我可能最终会编写代码,因为我的猜测是不会花太长时间来处理 .

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

2 回答

  • 3

    我会将你的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

    import timeit
    s = """paragraph = "five hundred to one hundred words separated by spaces"
    array_of_strings = set(['hundred', 'spaces', ])  # make a set..
    
    set(paragraph.split()).intersection(array_of_strings)
    """
    t = timeit.Timer(stmt=s)
    print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
    
  • 1

    如果使用列表,请先对其进行排序并使用二进制搜索 .

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

    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)
    

相关问题