
运行了一个玩具性能示例后,我们现在将稍微偏离主题并将性能与
进行对比
一些 python 实现。首先让我们设置计算阶段,并提供命令行
python 脚本的功能。
import argparse
import time
import math
import numpy as np
import os
from numba import njit
from joblib import parallel, delayed
parser = argparse.argumentparser()
parser.add_argument("--workers", type=int, default=8)
parser.add_argument("--arraysize", type=int, default=100_000_000)
args = parser.parse_args()
# set the number of threads to 1 for different libraries
print("=" * 80)
print(
f"\nstarting the benchmark for {args.arraysize} elements "
f"using {args.workers} threads/workers\n"
)
# generate the data structures for the benchmark
array0 = [np.random.rand() for _ in range(args.arraysize)]
array1 = array0.copy()
array2 = array0.copy()
array_in_np = np.array(array1)
array_in_np_copy = array_in_np.copy()
这是我们的参赛者:
for i in range(len(array0)):
array0[i] = math.cos(math.sin(math.sqrt(array0[i])))
np.sqrt(array_in_np, out=array_in_np) np.sin(array_in_np, out=array_in_np) np.cos(array_in_np, out=array_in_np)
def compute_inplace_with_joblib(chunk):
return np.cos(np.sin(np.sqrt(chunk))) #parallel function for joblib
chunks = np.array_split(array1, args.workers) # split the array into chunks
numresults = parallel(n_jobs=args.workers)(
delayed(compute_inplace_with_joblib)(chunk) for chunk in chunks
)# process each chunk in a separate thread
array1 = np.concatenate(numresults) # concatenate the results
@njit
def compute_inplace_with_numba(array):
np.sqrt(array,array)
np.sin(array,array)
np.cos(array,array)
## njit will compile this function to machine code
compute_inplace_with_numba(array_in_np_copy)
这是计时结果:
in place in ( base python): 11.42 seconds in place in (python joblib): 4.59 seconds in place in ( python numba): 2.62 seconds in place in ( python numpy): 0.92 seconds
numba 出奇的慢!?难道是由于 mohawk2 在 irc 交流中关于此问题指出的编译开销造成的吗?
为了测试这一点,我们应该在执行基准测试之前调用compute_inplace_with_numba一次。这样做表明 numba 现在比 numpy 更快。
in place in ( base python): 11.89 seconds in place in (python joblib): 4.42 seconds in place in ( python numpy): 0.93 seconds in place in ( python numba): 0.49 seconds
n<-50000000
x<-runif(n)
start_time <- sys.time()
result <- cos(sin(sqrt(x)))
end_time <- sys.time()
# calculate the time taken
time_taken <- end_time - start_time
# print the time taken
print(sprintf("time in base r: %.2f seconds", time_taken))
Time in base R: 1.30 seconds
以上就是性能追求第二部分:Perl 与 Python的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号