/**
* 原文出处:
* 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}