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

所有干货送给大家,希望能够点赞支持一下!
边栏推荐
- The style of the mall can also change a lot. DIY can learn about it!
- Sword finger offer 06 Print linked list from end to end
- 面试官:你简历上说精通mysql,那你说下聚簇/联合/覆盖索引、回表、索引下推
- Mixed density network (MDN) for multiple regression explanation and code example
- Native JS dynamically add elements
- 剑指 Offer II 091. 粉刷房子
- Continuously improve the overall performance of adaoracle Oracle Oracle
- Highly concurrent optimized Lua + openresty+redis +mysql (multi-level cache implementation) + current limit +canal synchronization solution
- f_ Read function [easy to understand]
- Uncover gaussdb (for redis): comprehensive comparison of CODIS
猜你喜欢

剑指 Offer 09. 用两个栈实现队列

Sword finger offer 05 Replace spaces

Talk about the creation process of JVM objects

Several relationships of UML

The paid video at station B caused the up master to lose more than ten thousand fans
Classic deadlock scenario of multithreading and its solution (philosopher dining problem)

Don't underestimate the integral mall, its role can be great!

商城风格也可以很多变,DIY 了解一下!

Golang uses Mongo driver operation - increase (Advanced)

Describe your understanding of the evolution process and internal structure of the method area
随机推荐
JS中的==和===的区别(详解)
Desktop development (Tauri) opens the first chapter
不要再「外包」AI 模型了!最新研究发现:有些破坏机器学习模型安全的「后门」无法被检测到
Is it safe to open a stock account in Guoxin golden sun?
Lombok common notes
Sword finger offer 10- I. Fibonacci sequence
合宙Air32F103CBT6开发板上手报告
合宙Air32F103CBT6開發板上手報告
将一个文件写入到另一个文件的标记位置
Rapport de la main - d'oeuvre du Conseil de développement de l'aecg air32f103cbt6
Programmer vs hacker thinking | daily anecdotes
Super comprehensive custom deep copy function
Geographic location data storage scheme - redis Geo
NFT元宇宙发展能做什么?
异步处理容易出错的点
What is the NFT digital collection?
Several relationships of UML
04. binary tree
基于神经标签搜索,中科院&微软亚研零样本多语言抽取式摘要入选ACL 2022
读配置、讲原理、看面试真题,我只能帮你到这了。。。