• 第四部分:python性能技巧


    4.1 查询操作为主时,选择字典结构比list结构效率更高

    4.2 取list的交集、并集、差集时,可借助set数据结构
    如listintersection = list(set(lista)&set(listb))
    4.3 原则是尽量减少循环过程中的计算量,有多重循环的尽量将内层的计算提到上一层.所以可以在外层实现的内层计算要在外层完成,然后传值进去。
    4.4 python 中的字符串对象是不可改变的,因此对任何字符串的操作如拼接,修改等都将产生一个新的字符串对象,而不是基于原字符串.
    对于字符串的操作,尽量使用下列方法
    (1)在字符串连接的使用尽量使用 join() 而不是 + 号。
    (2)当对字符串可以使用正则表达式或者内置函数来处理的时候,选择内置函数。
    如 str.isalpha(),str.isdigit(),str.startswith(('x', 'yz')),str.endswith(('x', 'yz'))
    (3)对字符进行格式化比直接串联读取要快,因此要使用out = "<html>%s%s%s%s</html>" % (head, prologue, query, tail)
    4.5 尽量使用局部变量,避免全局变量,python访问局部变量的速度比访问全局变量的速度更快
    4.6 if done is not None 比语句 if done != None 更快
    4.7 使用级联比较 "x < y < z" 而不是 "x < y and y < z"
    4.8 build in 函数通常较快,add(a,b) 要优于 a+
    4.9 python内置了性能分析工具,如profile,hotshot,与cProfile.
    示例1, 以profile为例:
    import profile
    def profileTest():
    Total =1;
    for i in range(10):
    Total=Total*(i+1)
    print Total
    return Total
    if __name__ == "__main__":
    profile.run("profileTest()")
    运行结果:
    1
    2
    6
    24
    120
    720
    5040
    40320
    362880
    3628800
    5 function calls in 0.083 seconds

    Ordered by: standard name

    ncalls tottime percall cumtime percall filename:lineno(function)
    1 0.000 0.000 0.000 0.000 :0(range)
    1 0.082 0.082 0.082 0.082 :0(setprofile)
    1 0.000 0.000 0.000 0.000 <string>:1(<module>)
    1 0.000 0.000 0.083 0.083 profile:0(profileTest())
    0 0.000 0.000 profile:0(profiler)
    1 0.000 0.000 0.000 0.000 python.py:2(profileTest)
    4.10 常用的python 自带的优化工具,如 Psyco,Pypy,Cython,Pyrex

  • 相关阅读:
    socket---tcp初始化配置
    IIS安装扩展
    一、效率开发
    Asp.net Core 3.1 之NLog使用扩展
    一文揭秘如何利用AndroidGodEye 打造Android应用性能测试监控
    安卓app功能或自动化测试覆盖率统计(不用instrumentation启动app)
    性能测试系列四 压测常见的关注指标以及监控分析工具
    性能测试系列三 压测方式简单总结 和压测指标的来源
    性能测试系列二 何时介入性能测试
    性能测试系列一(性能测试基础知识)
  • 原文地址:https://www.cnblogs.com/lifeinsmile/p/5285069.html
Copyright © 2020-2023  润新知