当前位置:网站首页>一行代码可以做什么?
一行代码可以做什么?
2022-06-25 15:39:00 【七步编程】
hello,大家好,我是 Jackpop,硕士毕业于哈尔滨工业大学,曾在华为、阿里等大厂工作,如果你对升学、就业、技术提升等有疑惑,不妨交个朋友:
可以做的事情太多了!一行代码足以把程序的执行速度提升超过10000倍!
缓存是一项从底层到高层都广泛应用的技术,无论是前端还是后端,有一定开发经验的程序员对缓存应该都不陌生。缓存是指可以进行高速数据交换的存储器,它先于内存与CPU交换数据,因此速率很快。
在Python开发过程中,有一些函数的结果可能会被反复调用,如果这个函数耗时较少还无伤大雅。
但是,如果一个函数耗时10分钟,或者频繁的发送rest请求,那么耗时就会呈现非线性上升。
那么,对于很多开发人员抱怨的Python,是否能够通过缓存来提升它的开发效率?
答案是肯定的!
本文就来介绍如果利用缓存这项技术,实现1行代码提升Python执行速度。
LRU
不同的编程语言,会有不同 的缓存策略,例如,通过哈希映射、优先级队列等实现缓存。因此,不同的编程语言,在缓存的解决方案方面具有很大差异,可能需要几分钟,也可能需要几小时。
但是,在Python中,标准工具包functools实现了一种名为LRU(Least Recently Used)的缓存策略,可以通过传入参数,来设定缓存最近多少次的计算结果,如果传入参数为None,那么会进行无限缓存。
现在,为了让大家更加容易理解,先来举一个例子,
import time as tt
def func():
num = 0
for i in range(10):
num += i
return num
def main():
return func() + func() + func() + func() + func() + func() + func()
t1 = tt.time()
main()
print("Time taken: {}".format(tt.time() - t1))
# 9.05990e-6
在这个示例中,反复的调用了func函数,总共耗时为0.009秒。
下面,通过functools工具包下LRU缓存再跑一下,
import time as tt
import functools
@functools.lru_cache(maxsize=5)
def func():
num = 0
for i in range(10):
num += i
return num
def main():
return func() + func() + func() + func() + func() + func() + func()
t1 = tt.time()
main()
print("Time taken: {}".format(tt.time() - t1))
# 4.768371e-06
通过数据对比,发现运行时间减少了将近50%。
在调用lru_cache时,需要配置一个maxsize的参数,它代表着缓存最近几次的函数计算结果,如果参数为none则不进行缓存。
通过前面的对比,会发现利用缓存机制时间差别会很大,这是由于,重复调用函数,需要反复执行计算过程,而利用缓存,我们只需要进行快速读写,不再需要重复执行计算过程,这样会节省大部分时间。
但是,由于前面计算过程较为简单,只涉及简单的加法运算,在耗时方面给人直观的感受并不是很强烈。
那下面在以另外斐波那契数列的例子进行对比一下。
应该很多同学对斐波那契数列都不陌生,一个很典型的递归问题,在教材上也频繁的出现。
由于它递归计算的过程中,还会用到之前计算的结果,因此会涉及较多的重复计算,下面先看一下正常计算的耗时情况。
import time as tt
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
t1 = tt.time()
fib(30)
print("Time taken: {}".format(tt.time() - t1))
# 0.2073
加一行@functools.lru_cache(maxsize=5) 之后,看看效果:
import time as tt
import functools
@functools.lru_cache(maxsize=5)
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
t1 = tt.time()
fib(30)
print("Time taken: {}".format(tt.time() - t1))
# 1.811981e-05
0.2073秒对比2.0981e-5秒之间差了4个量级,快了10000+倍!这样给人的直观感受应该就非常强烈了。
在涉及一些简单运算的过程中,即便是重复计算也无伤大雅。但是,如果涉及大量数据计算或者网络请求这类耗时的计算,利用缓存机制,只需要1行代码就可以节省可观的时间。既比重复计算节省时间,也要比多余定义变量简单。
干货
最近,为了方便大家,我花费了半个月的时间把这几年来收集的各种技术干货整理到一起,其中内容包括但不限于Python、机器学习、深度学习、计算机视觉、推荐系统、Linux、工程化、Java,内容多达5T+,我把各个资源下载链接整理到一个文档内,目录如下:

所有干货送给大家,希望能够点赞支持一下!
边栏推荐
- LeCun预言AGI:大模型和强化学习都是斜道!我的「世界模型」才是新路
- 说下你对方法区演变过程和内部结构的理解
- Practice of geospatial data in Nepal graph
- MT60B1G16HC-48B:A美光内存颗粒FBGA代码D8BNK[通俗易懂]
- MySQL installation tutorial
- Advanced SQL statement 1 of Linux MySQL database
- Converting cifar10 datasets
- [issue 24] one year experience of golang to develop futu
- f_read 函数[通俗易懂]
- Sword finger offer 07 Rebuild binary tree
猜你喜欢

Sword finger offer 06 Print linked list from end to end

Yadali brick playing game based on deep Q-learning

Uncover gaussdb (for redis): comprehensive comparison of CODIS
Take you to the open source project of smart home: the preliminary configuration of zhiting home cloud and home assistant+ homebridge

golang使用mongo-driver操作——增(进阶)

The paid video at station B caused the up master to lose more than ten thousand fans

Sword finger offer 03 Duplicate number in array

面试官:你简历上说精通mysql,那你说下聚簇/联合/覆盖索引、回表、索引下推

读配置、讲原理、看面试真题,我只能帮你到这了。。。

VectorDraw Developer Framework 10.1001 Crack
随机推荐
js 给元素添加自定义属性
What is OA
Programmer vs hacker thinking | daily anecdotes
Asynchronous processing of error prone points
揭秘GaussDB(for Redis):全面对比Codis
TFIDF与BM25
Traversal and branch judgment of JS (case on June 24, 2022)
The style of the mall can also change a lot. DIY can learn about it!
Super comprehensive custom deep copy function
Cloning and importing DOM nodes
Report on Hezhou air32f103cbt6 development board
Continuously improve the overall performance of adaoracle Oracle Oracle
Resolve Visio and office365 installation compatibility issues
Multithreading, parallelism, concurrency, thread safety
剑指 Offer 03. 数组中重复的数字
Read the configuration, explain the principle and read the interview questions. I can only help you here...
QC, QA, IPQC, JQE, DQA, SQE, DQC, MQC, IQC, FQC, OQC
Startup and shutdown of appium service
Sleep formula: how to cure bad sleep?
Share the code technology points and software usage of socket multi client communication