suchen

Heim  >  Fragen und Antworten  >  Hauptteil

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多秒。 这是为什么呢?会不会是因为位运算? 呃,先感谢大家解答

PHPzPHPz2893 Tage vor372

Antworte allen(2)Ich werde antworten

  • PHP中文网

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

    簡單來說,timeit 會執行代碼 1000000 次...,當然要花很久囉。

    這個 function 是用來測量某段代碼的平均運行時間,所以你必須除以他執行的次數。

    我改了一下你的代碼並且用 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

    結果:

    4.91142272949e-05
    2.89517600536e-05

    結果是單次的運行差不多...


    我回答過的問題: Python-QA

    Antwort
    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
    默认number=1000000
    默认要跑1000000次当然慢了...

    Antwort
    0
  • StornierenAntwort