python 加速运算
原文链接:https://blog.csdn.net/qq_27009517/article/details/103805099
一、加速查找
1.用set而非list
import time data = [i**2+1 for i in range(1000000)]
list_data = list(data)
set_data = set(data)
# normal
tic = time.time()
s = 1098987 in list_data
toc = time.time()
print('userd: {:.5f}s'.format(toc-tic))
# speed up
tic = time.time()
ss = 1098987 in set_data
toc = time.time()
print('userd: {:.5f}s'.format(toc-tic))
2.用dict而非两个list进行匹配查找
import time list_a = [i*2-1 for i in range(1000000)]
list_b = [i**2 for i in list_a]
dict_ab = dict(zip(list_a, list_b))
# normal
tic = time.time()
a = list_b[list_a.index(876567)]
toc = time.time()
print('userd: {:.5f}s'.format(toc-tic))
# speed up
tic = time.time()
aa = dict_ab.get(876567, None)
toc = time.time()
print('userd: {:.5f}s'.format(toc-tic))
二、加速循环,在循环体中避免重复计算,用循环机制代替递归函数
3.用for而非while
import time tic = time.time()
s, i = 0, 0
while i<100000:
i += 1
s += i
toc = time.time()
print('userd: {:.5f}s'.format(toc-tic)) tic = time.time()
s, i = 0, 0
for i in range(1, 100001):
i += 1
s += i
toc = time.time()
print('userd: {:.5f}s'.format(toc-tic))
三、利用库函数进行加速
4.用numba加速Python函数
import time tic = time.time()
def my_power(x):
return (x**2) def my_power_sum(n):
s = 0
for i in range(1, n+1):
s = s + my_power(i)
return s
s = my_power_sum(1000000)
toc = time.time()
print('used: {:.5f}s'.format(toc-tic)) # speed up
from numba import jit
tic = time.time()
@jit
def my_power(x):
return (x**2)
@jit
def my_power_sum(n):
s = 0
for i in range(1, n+1):
s = s + my_power(i)
return s
ss = my_power_sum(1000000)
toc = time.time()
print('used: {:.5f}s'.format(toc-tic))
代码是使用numpy做数字运算,并且常常有很多的循环,那么使用Numba就是一个很好的选择。numba不适合字典型变量和一些非numpy的函数,尤其是上面numba不能解析pandas,上面的函数内容在运行时也就无法编译。
5. 用map加速Python函数
import time tic = time.time()
res = [x**2 for x in range(1, 1000000, 3)]
toc = time.time()
print('used: {:.5f}s'.format(toc-tic)) # speed up tic = time.time()
res = map(lambda x:x**2, range(1, 1000000, 3))
toc = time.time()
print('used: {:.5f}s'.format(toc-tic))
6.用filter加速Python函数
import time tic = time.time()
res = [x**2 for x in range(1, 1000000, 3) if x%7==0]
toc = time.time()
print('used: {:.5f}s'.format(toc-tic)) # speed up tic = time.time()
res = filter(lambda x:x%7==0, range(1, 1000000, 3))
toc = time.time()
print('used: {:.5f}s'.format(toc-tic))
7. 用np.where加速if函数
import time import numpy as np array_a = np.arange(-100000, 100000)
tic = time.time()
relu = np.vectorize(lambda x: x if x>0 else 0)
arr = relu(array_a)
toc = time.time()
print('used: {:.5f}s'.format(toc-tic)) # speed up tic = time.time()
relu = lambda x:np.where(x>0, x, 0)
arrr = relu(array_a)
toc = time.time()
print('used: {:.5f}s'.format(toc-tic))
8.多线程thread加速
import time import numpy as np tic = time.time() def writefile(i):
with open(str(i)+'.txt', 'w') as f:
s = ('hello %d\n'%i) * 10000000
f.write(s)
for i in range(40,50, 1):
writefile(i) toc = time.time()
print('used: {:.5f}s'.format(toc-tic)) # speed up
import threading tic = time.time()
def writefile(i):
with open(str(i)+'.txt', 'w') as f:
s = ('hello %d\n'%i) * 10000000
f.write(s) thread_list = []
for i in range(10, 20, 1):
t = threading.Thread(target=writefile, args=(i, ))
t.setDaemon(True)
thread_list.append(t) for t in thread_list:
t.start()
for t in thread_list:
t.join() toc = time.time()
print('used: {:.5f}s'.format(toc-tic))
9.多线程multiprocessing加速
import time import numpy as np tic = time.time() def muchjob(x):
time.sleep(5)
return(x**2) ans = [muchjob(i) for i in range(8)]
toc = time.time()
print('used: {:.5f}s'.format(toc-tic)) # speed up
import multiprocessing tic = time.time() def muchjob(x):
time.sleep(5)
return x**2
pool = multiprocessing.Pool(processes=4)
res = []
for i in range(8):
res.append(pool.apply_async(muchjob, (i, )))
pool.close()
pool.join() toc = time.time()
print('used: {:.5f}s'.format(toc-tic))
python 加速运算的更多相关文章
- python各种运算优先级一览表
##python各种运算的优先级 运算符 描述 lambda Lambda表达式 or 布尔"或" and 布尔"与" not x 布尔"非" ...
- 斐波那契数列F(n)【n超大时的(矩阵加速运算) 模板】
hihocoder #1143 : 骨牌覆盖问题·一 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 骨牌,一种古老的玩具.今天我们要研究的是骨牌的覆盖问题: 我们有一个 ...
- matlab 中使用 GPU 加速运算
为了提高大规模数据处理的能力,matlab 的 GPU 并行计算,本质上是在 cuda 的基础上开发的 wrapper,也就是说 matlab 目前只支持 NVIDIA 的显卡. 1. GPU 硬件支 ...
- Python数值运算
算术运算 a=10 b=2 + 加-两个对象相加 a+b输出结果12 - 减-得到负数或是一个数减去另一个数 a - b输出结果8 * 乘-两个数相乘或是返回一个被重复若干次的字符串 a * b输出结 ...
- 3D Cube计算引擎加速运算
3D Cube计算引擎加速运算 华为达芬奇架构的AI芯片Ascend910,同时与之配套的新一代AI开源计算框架MindSpore. 为什么要做达芬奇架构? AI将作为一项通用技术极大地提高生产力,改 ...
- 10大python加速技巧
简介 目前非常多的数据竞赛都是提交代码的竞赛,而且加入了时间的限制,这就对于我们python代码的加速非常重要.本篇文章我们介绍在Python中加速代码的一些技巧.可能不是很多,但在一些大的循环或者函 ...
- python数学运算的类型转换
类型转换 Rational类实现了有理数运算,但是,如果要把结果转为 int 或 float 怎么办? 考察整数和浮点数的转换: >>> int(12.34) 12 >> ...
- Python数学运算
python中的加减乘除比其他的语言简单,不需要对其赋值变量 (1)加减乘除 ) #加法 ) #减法 ) #乘法 ) #除法 5.0 ) #乘方 (2)判断 判断返回的是True或者False ) # ...
- python 数据运算
算数运算:
随机推荐
- Apollo mqtt 服务器搭建
html { overflow-x: initial !important } :root { --bg-color: #ffffff; --text-color: #333333; --select ...
- vue菜单切换
HTML: <div id="box"> <ul> <li v-for= "(item,index) in arry"> & ...
- C语言运算符(杂项运算符 ↦ sizeof & 三元)
实列 1 #include <stdio.h> 2 3 int main() 4 { 5 int a = 4; 6 short b; 7 double c; 8 int* ptr; 9 1 ...
- Android太太太太太卷了,累了
我们聊到互联网行业的时候,一个不可避免的话题就是"内卷",而在程序员这个群体中,Android,绝对是卷得最厉害的. 毕竟前几年Android兴起的时候,入门门槛低,培训机构培养了 ...
- srt文件的时间轴平移处理
有时srt字幕文件与视频文件的时间不完全吻合,有一个时间差,这就需要对srt文件的时间轴进行平移,具备这个功能的软件很多,比如:Subtitle Tool, subresync, sabbu, Sub ...
- 北航面向对象OO第三单元——JML
简介 本单元借助JML(Java Modeling Language),训练了我们关于的"规格(specification)"的意识和思想 本单元代码难度较低,简单来讲就是给你规定 ...
- NOIP 模拟 $17\; \rm 世界线$
题解 \(by\;zj\varphi\) 此题经简单观察可发现,一个点的贡献就是这个点所能到的点减去它的出度 那么我们就可以暴力搜索,但是显然会超时,所以我们可以使用一个黑科技 \(\rm bitse ...
- 分布式redis自增
redis+springboot RedisUtil.java package com.meeno.chemical.common.redis; import java.util.Date; impo ...
- 6、二进制安装K8s之部署kubectl
二进制安装K8s之部署kubectl 我们把k8s-master 也设置成node,所以先master上面部署node,在其他机器上部署node也适用,更换名称即可. 1.在所有worker node ...
- Kafka 与 RabbitMQ 如何选择使用哪个?
目录 前言 如何选择? 开发语言 延迟队列 消息顺序性 优先级队列 消息留存 消息过滤 可伸缩行 小结 推荐阅读 前言 我们在工作中经常会用到异步消息,主要使用两种消息模式: 消息队列 发布/订阅 消 ...