本文主要是介绍Python 加减乘除左右移求幂运算符耗时对比(一清二楚),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
本文依次统计了Python3.5中
赋值= 加+ 连加+= 减- 乘* 幂** 除/ 整数除法// 先除再强制转换为整型 int(/) 取余% 右移>> 左移<< 取反=-
这十余种运算方式重复执行1000W次的耗时。(运行结果和结论在文章最下方)
代码如下:
from time import *iters = 10000000 # 1000w
x = 123456start_time = time()
for i in range(iters):tmp = i
end_time = time()
print('Assign = : ' + str((end_time - start_time) * 1000) + ' ms')start_time = time()
for i in range(iters):tmp = x + i# x = x + i
end_time = time()
print('Add + : ' + str((end_time - start_time) * 1000) + ' ms')tmp = 0
start_time = time()
for i in range(iters):tmp += i
end_time = time()
print('Serial add += : ' + str((end_time - start_time) * 1000) + ' ms')start_time = time()
for i in range(iters):tmp = x - i
end_time = time()
print('Sub - : ' + str((end_time - start_time) * 1000) + ' ms')start_time = time()
for i in range(iters):tmp = x * i
end_time = time()
print('Multi * : ' + str((end_time - start_time) * 1000) + ' ms')start_time = time()
for i in range(iters):tmp = x ** 2
end_time = time()
print('Pow **2 : ' + str((end_time - start_time) * 1000) + ' ms')start_time = time()
for i in range(iters):tmp = x ** 8
end_time = time()
print('Pow **8 : ' + str((end_time - start_time) * 1000) + ' ms')start_time = time()
for i in range(iters):tmp = pow(x, 2)
end_time = time()
print('pow(x, 2) : ' + str((end_time - start_time) * 1000) + ' ms')start_time = time()
for i in range(iters):tmp = pow(x, 8)
end_time = time()
print('pow(x, 8) : ' + str((end_time - start_time) * 1000) + ' ms')start_time = time()
for i in range(1, iters+1):tmp = x / i
end_time = time()
print('Div / : ' + str((end_time - start_time) * 1000) + ' ms')start_time = time()
for i in range(1, iters+1):tmp = x // i
end_time = time()
print('Int div // : ' + str((end_time - start_time) * 1000) + ' ms')start_time = time()
for i in range(1, iters+1):tmp = int(x / i)
end_time = time()
print('Div and Int() int(/) : ' + str((end_time - start_time) * 1000) + ' ms')start_time = time()
for i in range(1, iters+1):tmp = x % i
end_time = time()
print('Mod % : ' + str((end_time - start_time) * 1000) + ' ms')start_time = time()
for i in range(iters):tmp = x >> 1
end_time = time()
print('Right shift >> : ' + str((end_time - start_time) * 1000) + ' ms')start_time = time()
for i in range(iters):tmp = x << 1
end_time = time()
print('Left shift << : ' + str((end_time - start_time) * 1000) + ' ms')tmp = 1
start_time = time()
for i in range(iters):tmp = -tmp
end_time = time()
print('Neg =- : ' + str((end_time - start_time) * 1000) + ' ms')
两次运行结果:
其一:
其二:
结论:
- python中,加减乘除左右移执行时间相差不大
- 用x=-x的取反操作远远快于x*=-1
- 用x*x的乘法求平方远快于x**2,**求幂操作会随着幂指数的增加而增加耗时
- pow(x, y)略慢于x**y
- 类型转换比较耗时
环境:
python3.5
这篇关于Python 加减乘除左右移求幂运算符耗时对比(一清二楚)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!