0.903 profiler.py:3(sum_of_squares)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Global scope:
2 function calls in 1.358 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 1.358 1.358 1.358 1.358 profiler.py:10(sum_of_squares_g)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
如何优化 python 函数的性能
前面我们知道,Python 代码在函数中运行往往比在全局范围内运行要快得多
如果想要进一步提高 python 函数代码效率,不妨考虑一下使用局部变量而不是全局变量
另一种方法是尽可能使用内置函数和库。Python 的内置函数是用 C 实现的,比 Python 快得多
比如 NumPy 和 Pandas,也是用 C 或 C++ 实现的,它们比实现同样功能的 Python 代码速度更快
又比如同样是实现数字求和的功能,python 内置的 sum
函数要比你自己编写函数速度更快