Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用python对数学运算进行基准测试_Python_Python 3.x_Math_Benchmarking - Fatal编程技术网

用python对数学运算进行基准测试

用python对数学运算进行基准测试,python,python-3.x,math,benchmarking,Python,Python 3.x,Math,Benchmarking,代码运行速度越快越好。如果我想构建一个代码来执行一些数值模拟,通常情况下,我有可能将一个方程展开为“原始”操作 我一直在想一些数学运算的计算成本是多少: # Import necessary modules import numpy as np import time import matplotlib.pyplot as plt # Define functions to test def summation(value): return value+value def s

代码运行速度越快越好。如果我想构建一个代码来执行一些数值模拟,通常情况下,我有可能将一个方程展开为“原始”操作

我一直在想一些数学运算的计算成本是多少:

# Import necessary modules
import numpy as np
import time
import matplotlib.pyplot as plt

# Define functions to test
def summation(value):
    return value+value
    
def subtraction(value):
    return value-value

def multiplication(value):
    return value*value

def division(value):
    return value/2

def square(value):
    return value**2
    
def sin(value):
    return np.sin(value)

# Function that will evaluate the execution time
def time_execution(func, valueToEvaluate, nOuterCycles, nCycles):
    store = np.zeros( nOuterCycles)
    for i in range( nOuterCycles):
        start = time.time()
        for j in range(nCycles):
            func(valueToEvaluate)
        end = time.time()
        store[i]=(end-start)
    
    meanCycleTime=np.round(np.mean(store)*1e9/nCycles)
    stdCycleTime=np.round(np.std(store)*1e9/nCycles,2)
    print("%s takes %s ns.\u00B1 %s ns per loop (mean ± std. dev. of %s runs %s loops each)" %(func.__name__,meanCycleTime,stdCycleTime,nOuterCycles,nCycles))
    return func.__name__,meanCycleTime,stdCycleTime

# Time execution parameters
nCycles=1000000
nOuterCycles=5
value=1.1

# Executes the functions and appends the results to a list
valuesForPlot=[]
valuesForPlot.append(time_execution(summation,value,nOuterCycles,nCycles))
valuesForPlot.append(time_execution(subtraction,value,nOuterCycles,nCycles))
valuesForPlot.append(time_execution(multiplication,value,nOuterCycles,nCycles))
valuesForPlot.append(time_execution(division,value,nOuterCycles,nCycles))
valuesForPlot.append(time_execution(square,value,nOuterCycles,nCycles))
valuesForPlot.append(time_execution(sin,value,nOuterCycles,nCycles))

    
## Bar plot
# Collect entries for the plot
x_names =  []
y_values = []
error =    []

for i in valuesForPlot:
    x_names.append(i[0])
    y_values.append(i[1])
    error.append(i[2])

fig, ax = plt.subplots()
ax.bar(x_names, y_values, yerr=error,align='center', alpha=0.5, ecolor='black', capsize=10)
ax.set_ylabel('Time of operation [s]')
ax.yaxis.grid(True)
plt.tight_layout()
plt.show()
  • 总和
  • 减法
  • 倍增
  • 分部
  • 平方
  • 三角函数(如sin)
我创建了以下脚本来度量此操作:

# Import necessary modules
import numpy as np
import time
import matplotlib.pyplot as plt

# Define functions to test
def summation(value):
    return value+value
    
def subtraction(value):
    return value-value

def multiplication(value):
    return value*value

def division(value):
    return value/2

def square(value):
    return value**2
    
def sin(value):
    return np.sin(value)

# Function that will evaluate the execution time
def time_execution(func, valueToEvaluate, nOuterCycles, nCycles):
    store = np.zeros( nOuterCycles)
    for i in range( nOuterCycles):
        start = time.time()
        for j in range(nCycles):
            func(valueToEvaluate)
        end = time.time()
        store[i]=(end-start)
    
    meanCycleTime=np.round(np.mean(store)*1e9/nCycles)
    stdCycleTime=np.round(np.std(store)*1e9/nCycles,2)
    print("%s takes %s ns.\u00B1 %s ns per loop (mean ± std. dev. of %s runs %s loops each)" %(func.__name__,meanCycleTime,stdCycleTime,nOuterCycles,nCycles))
    return func.__name__,meanCycleTime,stdCycleTime

# Time execution parameters
nCycles=1000000
nOuterCycles=5
value=1.1

# Executes the functions and appends the results to a list
valuesForPlot=[]
valuesForPlot.append(time_execution(summation,value,nOuterCycles,nCycles))
valuesForPlot.append(time_execution(subtraction,value,nOuterCycles,nCycles))
valuesForPlot.append(time_execution(multiplication,value,nOuterCycles,nCycles))
valuesForPlot.append(time_execution(division,value,nOuterCycles,nCycles))
valuesForPlot.append(time_execution(square,value,nOuterCycles,nCycles))
valuesForPlot.append(time_execution(sin,value,nOuterCycles,nCycles))

    
## Bar plot
# Collect entries for the plot
x_names =  []
y_values = []
error =    []

for i in valuesForPlot:
    x_names.append(i[0])
    y_values.append(i[1])
    error.append(i[2])

fig, ax = plt.subplots()
ax.bar(x_names, y_values, yerr=error,align='center', alpha=0.5, ecolor='black', capsize=10)
ax.set_ylabel('Time of operation [s]')
ax.yaxis.grid(True)
plt.tight_layout()
plt.show()
在我的计算机上,我的结果如下:

summation takes 85.0 ns.± 2.99 ns per loop (mean ± std. dev. of 5 runs 1000000 loops each)
subtraction takes 82.0 ns.± 2.25 ns per loop (mean ± std. dev. of 5 runs 1000000 loops each)
multiplication takes 74.0 ns.± 0.87 ns per loop (mean ± std. dev. of 5 runs 1000000 loops each)
division takes 85.0 ns.± 1.52 ns per loop (mean ± std. dev. of 5 runs 1000000 loops each)
square takes 103.0 ns.± 2.06 ns per loop (mean ± std. dev. of 5 runs 1000000 loops each)
sin takes 779.0 ns.± 2.61 ns per loop (mean ± std. dev. of 5 runs 1000000 loops each)
我在网上(和其他网站)读到,我选择的数学运算应该按以下顺序排列: 求和和和减法<乘法<除法<平方<三元函数。然而,我得到的求和、减法、乘法和除法的结果并没有实质性的差别。有什么特别的原因吗


向您致以最诚挚的问候

Change
2
在您将其划分为变量时,它应该需要更长的时间来计算。同样,
a*a
可能比
a*b
快。仅调用这些函数所需的时间可能超过计算这些简单数学运算所需的时间。单个运算所需的时间可以忽略不计。加快速度的第一步是使用数组操作调用numpy。避免循环。可能是像numba这样的方法来编译机器代码。。。。还注意到Python有任意大小的整数,所以你会看到与大的数字更明显的差别。如果速度很重要,使用像C++的本地语言,而不是Python。Python对于这种性能度量是无用的,因为解释器的开销远远超过了基本算术运算的成本。在x86上,加法、减法和乘法在每个核的每个周期执行一个操作,或者换句话说,在现代机器上,这些操作只需几分之一纳秒()。将除法中的
2
更改为变量,计算时间也会更长。类似地,
a*a
可能比
a*b
快。仅调用这些函数所需的时间可能超过计算这些简单数学运算所需的时间。单个运算所需的时间可以忽略不计。加快速度的第一步是使用数组操作调用numpy。避免循环。可能是像numba这样的方法来编译机器代码。。。。还注意到Python有任意大小的整数,所以你会看到与大的数字更明显的差别。如果速度很重要,使用像C++的本地语言,而不是Python。Python对于这种性能度量是无用的,因为解释器的开销远远超过了基本算术运算的成本。在x86上,加法、减法和乘法在每个内核的每个周期执行一个操作,或者换句话说,在现代机器上,这些操作的成本只有几分之一纳秒()。