python的分段测试和优化

/**

*  原文出处:

*  https://toucantoco.com/en/tech-blog/tech/python-performance-optimization

*  原文作者: Sylvain Josserand

*  原文发布: 2017-1-16

*/


第一个方案: 利用timeit 模块

#! /usr/bin/python

# -*- coding: utf-8 -*-


import random
import timeit


def wirte_sorted_letters(nb_letters=10**7):
    """
    首先创建一个长度为10的7次方的随机字符串;
    然后对字符串排序;
    然后写入文件。
    """
    random_string = ''
    for i in range(nb_letters):
        random_string += random.choice('abcdefghijklmnopqrstuvwxyz')

   sorted_string = sorted(random_string)

    with open("Sorted_text.txt", "w") as sorted_text:
        for character in sorted_string:
            sorted_text.write(character)

    return True


def main():

    sec1 = timeit.timeit(stmt=wirte_sorted_letters, number=1)
    print(sec1)

if __name__ == '__main__':
    main()

在我的机器上,timeit 计算出来的时间是14秒多点。



第二种方案:命令行调用cProfile模块。

然后去掉代码用引用 timeit 的部分。并且删除掉生成的文件。

在 cmd 中执行:

python -m cProfile -s tottime main.py

         62309408 function calls (62309365 primitive calls) in 20.256 seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    6.599    6.599   20.231   20.231 main.py:8(wirte_sorted_letters)
 10000000    4.216    0.000    5.841    0.000 random.py:222(_randbelow)
 10000000    3.320    0.000    9.691    0.000 random.py:252(choice)
 10000000    2.189    0.000    2.189    0.000 {method 'write' of '_io.TextIOWrapper' objects}
        1    1.753    1.753    1.753    1.753 {built-in method builtins.sorted}
 12307695    1.180    0.000    1.180    0.000 {method 'getrandbits' of '_random.Random' objects}
 10000012    0.530    0.000    0.530    0.000 {built-in method builtins.len}
 10000000    0.445    0.000    0.445    0.000 {method 'bit_length' of 'int' objects}
        1    0.021    0.021   20.253   20.253 main.py:26(main)
       30    0.001    0.000    0.001    0.000 {built-in method nt.stat}
        1    0.001    0.001    0.001    0.001 {built-in method _imp.create_dynamic}
        1    0.001    0.001    0.001    0.001 {built-in method io.open}
       23    0.000    0.000    0.001    0.000 <frozen importlib._bootstrap_external>:1233(find_spec)
        3    0.000    0.000    0.000    0.000 {built-in method marshal.loads}
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值