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 数据运算
算数运算:
随机推荐
- JVM的内存管理机制-转载
JVM的内存管理机制 一.JVM的内存区域 对于C.C++程序员来说,在内存管理领域,他们既拥有每一个对象的"所有权",又担负着每一个对象生命开始到终结的维护责任. 对Java程序 ...
- 解决ftp登录问题:500 OOPS: cannot change directory:/home/xxx 500 OOPS: child died
.personSunflowerP { background: rgba(51, 153, 0, 0.66); border-bottom: 1px solid rgba(0, 102, 0, 1); ...
- TextLineCodecFactory笔记
Mina的TextLineCodecFactory将字符串编码为字节流,将字节流解码为字符串,下面是使用中遇到的两个问题. TextLineCodecFactory改变了message的类型 acce ...
- 项目中redisTemplate设置的key,redis客户端上查询不到的问题
再项目使用了redis储存key,测试需要在客户端删除对应的key,发现查询不到对应的key redis客户端: 发现redisTemplate实际存进去的key会多了几个字符 原因:程序中对key没 ...
- 更换Swing界面中的窗口图标
Swing 窗口图标更换 因为需要,所以要更改窗口的图标,很简单 在代码中加上 Image icon = Toolkit.getDefaultToolkit().getImage("图片地址 ...
- Java MyEclipse:The type java.lang.CharSequence cannot be resolved. It is indirectly referen
从svn上下载项目后配置weblogic后启动报错: myeclipse The type java.lang.CharSequence cannot be resolved. It is indi ...
- [源码解析] 深度学习流水线并行Gpipe(1)---流水线基本实现
[源码解析] 深度学习流水线并行Gpipe(1)---流水线基本实现 目录 [源码解析] 深度学习流水线并行Gpipe(1)---流水线基本实现 0x00 摘要 0x01 概述 1.1 什么是GPip ...
- noip29
T1 以下的LIS代指最长不降子序列. 考场看到取模,便想到了之前写过的Medain,取模操作让序列分布均匀,对应到本题上,既然是求LIS,那它应该是有循环节的,后来打表证实确实是有. 然后,我码了个 ...
- NOIP 模拟 $27\; \rm 牛半仙的妹子Tree$
题解 \(by\;zj\varphi\) 很妙的虚树题. 考虑若没有操作 \(2\),那么直接记录一下扩散到它的最短时间和询问时间相比即可,可以当作一个树上最短路. 有 \(2\) 操作怎么办,将操作 ...
- Python3 * 和 ** 运算符
1.算数运算 * 代表乘法 ** 代表乘方 1>>> 2 * 52103>>> 2 ** 5432 2.函数形参 *args 和 **kwargs 主要用于函数定 ...