• timeit 性能测试


    1. timeit模块

    可以用来测试一小段Python代码的执行速度

    计时器类:class timeit.Timer(stmt='pass', setup='pass', timer=<timer function>)

    Timer是测量小段代码执行速度的

      stmt:是要测试的代码语句(statment),也可以传方法名

      setup:运行语句时,需要的设置,例如为了执行time.time()要引入time

      timer:是一个定时器函数,与平台有关,不需要处理

    函数:timeit.Timer.timeit(number=1000000)

      Timer类中测试语句执行速度的对象方法

      number参数是测试代码时的测试次数,默认为1000000

      方法返回执行代码的平均耗时,一个float类型的秒数

     
    
    # -*- coding:utf-8 -*-
    def test1():
        l = []
        for i in range(3000):
            l.append(i)
    
    def test2():
        l = []
        for i in range(3000):
            l.insert(0, i)
    
    def test3():
        l = [i for i in range(3000)]
    
    def test4():
        l = list(range(3000))
    
    def test5():
        l = []
        for i in range(3000):
            l.extend([i])
    
    def test6():
        l = []
        for i in range(3000):
            l = l + [i]
    
    def test7():
        l = []
        for i in range(3000):
            l += [i]
    
    from timeit import Timer
    
    print('开始测试')
    t1 = Timer("test1()", "from __main__ import test1")
    print("append:			", t1.timeit(number=1000), "")
    t2 = Timer("test2()", "from __main__ import test2")
    print("insert:		", t2.timeit(number=1000), "")
    t3 = Timer("test3()", "from __main__ import test3")
    print("推倒:		", t3.timeit(number=1000), "")
    t4 = Timer("test4()", "from __main__ import test4")
    print("list:		", t4.timeit(number=1000), "")
    t5 = Timer("test5()", "from __main__ import test5")
    print("extend:		", t5.timeit(number=1000), "")
    t6 = Timer("test6()", "from __main__ import test6")
    print("+:		", t6.timeit(number=1000), "")
    t7 = Timer("test7()", "from __main__ import test7")
    print("+=:		", t7.timeit(number=1000), "")
    print('结束测试')
  • 相关阅读:
    提取Word中的标题以及做标记的内容
    洪水暴发时怎么办?
    面朝大海,春暖花开
    洪水过后要注意哪些事项?
    JS判断客户端是否是iOS或者Android
    关于取消网页接口请求的一些思考
    gkENGINE渲染优化
    RMI拓展
    序列化和反序列化
    cve20201938/cve202010487
  • 原文地址:https://www.cnblogs.com/hude/p/12950312.html
Copyright © 2020-2023  润新知