zoukankan      html  css  js  c++  java
  • 第四部分: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

  • 相关阅读:
    Python基本数据类型
    Python基础之杂货铺
    第五篇:白话tornado源码之褪去模板的外衣
    第四篇:白话tornado源码之褪去模板外衣的前戏
    第三篇:白话tornado源码之请求来了
    重构if-else方法
    linux-常用命令
    Element-UI的远程搜索输入框实现
    下载功能-vue
    上传功能-弹窗实现-vue
  • 原文地址:https://www.cnblogs.com/lifeinsmile/p/5285069.html
Copyright © 2011-2022 走看看