当前位置:网站首页>一行代码可以做什么?
一行代码可以做什么?
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+,我把各个资源下载链接整理到一个文档内,目录如下:

所有干货送给大家,希望能够点赞支持一下!
边栏推荐
- What is OA
- Multithreading, parallelism, concurrency, thread safety
- Converting cifar10 datasets
- Power representation in go language
- golang reverse a slice
- Describe your understanding of the evolution process and internal structure of the method area
- Interviewer: your resume says you are proficient in mysql, so you say cluster / Union / overlay index, table return, index push down
- js 给元素添加自定义属性
- Introduction to database transactions
- Do you want to go to an outsourcing company? This article will give you a comprehensive understanding of outsourcing pits!
猜你喜欢

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

说下你对方法区演变过程和内部结构的理解
MySQL installation tutorial

剑指 Offer 04. 二维数组中的查找

TFIDF与BM25

Golang uses Mongo driver operation - increase (Advanced)

Talk about the creation process of JVM objects

Sword finger offer 04 Find in 2D array

MySQL transaction characteristics and implementation principle

Uncover gaussdb (for redis): comprehensive comparison of CODIS
随机推荐
Analysis of the concept of metacosmic system
Uncover gaussdb (for redis): comprehensive comparison of CODIS
Share the code technology points and software usage of socket multi client communication
Continuously improve the overall performance of adaoracle Oracle Oracle
The style of the mall can also change a lot. DIY can learn about it!
JS add custom attributes to elements
Check whether the port number is occupied
Jz-065 path in matrix
[issue 24] one year experience of golang to develop futu
地理位置数据存储方案——Redis GEO
将一个文件写入到另一个文件的标记位置
Advanced SQL statement 1 of Linux MySQL database
Describe your understanding of the evolution process and internal structure of the method area
Leetcode topic [array]-34- find the first and last positions of elements in a sorted array
Classic deadlock scenario of multithreading and its solution (philosopher dining problem)
JS的注释
JS的遍历和分支判断(2022年6月24日案例)
Golang open source streaming media audio and video network transmission service -lal
Startup and shutdown of appium service
Ten routing strategies for distributed task scheduling platform XXL job