zoukankan      html  css  js  c++  java
  • 029 timeit

    测量生成列表的时间

    • 像是 C, Js 中把函数作为参数传入
    >>> import timeit
    >>> func = '''
    ... arr = []
    ... for i in range(1000):
    ...   arr.append(i)
    ... '''
    >>> t1 = timeit.timeit(stmt=func, number=10000)  # 可近似看成函数指针
    >>> t2 = timeit.timeit(stmt="[i for i in range(1000)]", number=10000)
    >>> t1
    1.0912232999999105
    >>> t2
    0.5270981999999549
    
    • 可以看出,列表生成式比 list.append()

    测量函数运行时间

    例1

    import timeit
    
    
    def func(num=3):
        for i in range(num):
            print(f"Repeat for {i}.")
    
    
    if __name__ == "__main__":
        t = timeit.timeit(stmt=func, number=5)
        print(t)
    

    >>>

    Repeat for 0.
    Repeat for 1.
    Repeat for 2.
    Repeat for 0.
    Repeat for 1.
    Repeat for 2.
    Repeat for 0.
    Repeat for 1.
    Repeat for 2.
    Repeat for 0.
    Repeat for 1.
    Repeat for 2.
    Repeat for 0.
    Repeat for 1.
    Repeat for 2.
    0.0009049000000231899
    

    例2

    import timeit
    
    
    def func(num=3):
        for i in range(num):
            print(f"Repeat for {i}.")
    
    
    if __name__ == "__main__":
        t = timeit.timeit(stmt=func, setup="func"+"num=5", number=5)
        # t = timeit.timeit(func, setup="funcnum=5", number=5) 也行,但不直观
        print(t)
    

    >>>

    Repeat for 0
    Repeat for 1
    Repeat for 2
    Repeat for 0
    Repeat for 1
    Repeat for 2
    Repeat for 0
    Repeat for 1
    Repeat for 2
    Repeat for 0
    Repeat for 1
    Repeat for 2
    Repeat for 0
    Repeat for 1
    Repeat for 2
    0.008177499999874271
    

    例3

    >>> s = '''
    ... def func(num):
    ...   for i in range(num):
    ...     print(f"Repeat for {i}")
    ... '''
    >>> t = timeit.timeit(stmt="func(num)", setup=s+"num=3", number=5)
    Repeat for 0
    Repeat for 1
    Repeat for 2
    Repeat for 0
    Repeat for 1
    Repeat for 2
    Repeat for 0
    Repeat for 1
    Repeat for 2
    Repeat for 0
    Repeat for 1
    Repeat for 2
    Repeat for 0
    Repeat for 1
    Repeat for 2
    >>> t
    0.0020025999997415056
    
  • 相关阅读:
    Linux学习之网络基础
    C# 随笔
    最牛B的编码套路
    c++ Primer 第七章不熟悉知识点总结
    oracle求表的倒数二行数据
    c++ Primer 第六章不熟悉知识点总结
    c++ Primer 第五章不熟悉知识点总结
    c++ Primer 第四章不熟悉知识点总结
    c++ Primer 第三章不熟悉知识点总结
    骑驴找马
  • 原文地址:https://www.cnblogs.com/yorkyu/p/12037517.html
Copyright © 2011-2022 走看看