search

Home  >  Q&A  >  body text

python timeit测量代码运行时间, 好像不对

def is_unique_char(string):
    if len(string) > 256:
        return True

    record = 0L

    for ch in string:
        # print record
        ch_val = ord(ch)

        if (record & (1 << ch_val)) > 0:
            return False

        record |= (1 << ch_val)

    return True


import string
s1 = string.ascii_letters + string.digits


if __name__ == '__main__':
    import timeit
    print is_unique_char(s1)
    print timeit.timeit("is_unique_char(s1)",
            setup="from __main__ import is_unique_char, s1")
            

代码如上, is_unique_char 就是一个包含位运算的函数(具体作用不重要)
运行代码, 秒出print is_unique_char(s1)的结果, 但是timeit测量需要30多秒。 这是为什么呢?会不会是因为位运算? 呃,先感谢大家解答

PHPzPHPz2890 days ago364

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 09:06:07

    To put it simply, timeit 會執行代碼 1000000 times..., of course it will take a long time.

    This function is used to measure the average running time of a certain piece of code, so you must divide it by the number of times it is executed.

    I changed your code and tested it using time.time:

    # uc.py
    
    import string
    
    def is_unique_char(string):
        if len(string) > 256:
            return True
    
        record = 0L
    
        for ch in string:
            # print record
            ch_val = ord(ch)
    
            if (record & (1 << ch_val)) > 0:
                return False
    
            record |= (1 << ch_val)
    
        return True
    
    s1 = string.ascii_letters + string.digits
    import timeit
    import time
    from uc import is_unique_char, s1
    
    if __name__ == '__main__':
        btime = time.time()
        is_unique_char(s1)
        etime = time.time()
        print etime - btime
        print timeit.timeit("is_unique_char(s1)", setup="from uc import is_unique_char, s1")/1000000

    Result:

    4.91142272949e-05
    2.89517600536e-05

    The result is that a single run is almost the same...


    Questions I answered: Python-QA

    reply
    0
  • 黄舟

    黄舟2017-04-18 09:06:07

    https://docs.python.org/2/library/timeit.html

    timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)
    

    Create a Timer instance with the given statement, setup code and timer function and run its timeit() method with number executions

    number executions
    Defaultnumber=1000000
    The default is to run 1,000,000 times, which is of course slow...

    reply
    0
  • Cancelreply