Error in user YAML: (<unknown>): could not find expected ':' while scanning a simple key at line 3 column 1
---
- oeasy Python 0239
- 这是 oeasy 系统化 Python 教程,从基础一步步讲,扎实、完整、不跳步。愿意花时间学,就能真正学会。
本教程同步发布在:
个人网站: `https://oeasy.org`
蓝桥云课: `https://www.lanqiao.cn/courses/3584`
GitHub: `https://github.com/overmind1980/oeasy-python-tutorial`
Gitee: `https://gitee.com/overmind1980/oeasypython`
---- 上次比较了递归(recursion)和循环(loop)
- 一般来讲循环所用时间较少
- 递归可能会有大量重复的函数调用
- 查看调用过程和时间可以用viztrace
- 不过这个有点太重了
- 有没有快速查看函数运行时间的方法呢?
- 我们以前用过这个
- time.time()
- 重写代码
- 运行结果为
- e-6
- μs(microsecond)
- 微秒
- 这两个差多少倍呢?
- 先把两个py文件导入进来
- 速度翻了35倍
- 有没有更快速的计时方式呢?
- 尝试构造代码
- 为什么每次执行时间不一样?
-
具体运行的时候
- 会和很多因素相关
- 当时的cpu内存状况等
- 当前内存情况
- 会和很多因素相关
-
怎么时间这么长呢?
-
1s以上
- 以下为循环
import timeit
def fibo_loops(n): # return Fibonacci series up to n
"""Return a list containing the Fibonacci series up to n."""
result = []
a, b = 0, 1
while a < n:
result.append(a) # see below
a, b = b, a+b
return result
fibo_loops(10000)- 以下为递归
import time
def fibo_recursive(n): # write Fibonacci n
"""Return nth element of the Fibonacci series up to n."""
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibo_recursive(n-1) + fibo_recursive(n-2)
def fibo_get_series(n):
"""Return a list containing the Fibonacci series up to n."""
i = 0
result = 0
l = []
while result<n :
l.append(result)
i += 1
result = fibo_recursive(i)
return l
fibo_get_series(10000)
- 查看手册
- timeit有个参数(parameter)number
- 有个默认值(default value)
- 1000000
- 这是计算100以内的斐波那契数列
- 如果计算10000以内的会有什么区别么?
- 好像差距在扩大😱
- 这次研究了计时函数timeit.timeit()
- 可以把一段代码的文本作为参数传进来
- 然后重复执行number次
- 把这个时间记录下来
- 这样就可以比较递归和循环的运行时间
- 实践出真知
- 得出哪个函数更好
- 或者说得出哪个算法更好
- 很明显是循环比递归快很多
- 关键递归有很多重复的内容
- 我可以把这些重复的部分给优化了么?🤔
- 我们下次再说👋
- 本文来自 oeasy Python 系统教程。
- 想完整、扎实学 Python,
- 搜索 oeasy 即可。




















