编程语言
首页 > 编程语言> > .NET数组比IronPython中的列表慢?

.NET数组比IronPython中的列表慢?

作者:互联网

我在IronPython中基于代码here做了以下矩阵乘法基准测试:

from System import Random
from System.Diagnostics import Stopwatch

def zero(m,n):
    # Create zero matrix
    new_matrix = [[0 for row in range(n)] for col in range(m)]
    return new_matrix

def rand(m,n):
    # Create random matrix
    rnd = Random(1)
    new_matrix = [[rnd.NextDouble() for row in range(n)] for col in range(m)]
    return new_matrix

def show(matrix):
    # Print out matrix
    for col in matrix:
        print col 

def mult(matrix1,matrix2):
    # Matrix multiplication
    if len(matrix1[0]) != len(matrix2):
        # Check matrix dimensions
        print 'Matrices must be m*n and n*p to multiply!'
    else:
        # Multiply if correct dimensions
        watch = Stopwatch()
        print 'mult1 start....'
        watch.Start()
        new_matrix = zero(len(matrix1),len(matrix2[0]))
        for i in range(len(matrix1)):
            for j in range(len(matrix2[0])):
                for k in range(len(matrix2)):
                    new_matrix[i][j] += matrix1[i][k]*matrix2[k][j]
        watch.Stop()
        print 'mult1 end.'
        print watch.ElapsedMilliseconds
        return new_matrix

from System import Array

def ListToArray(matrix):
    n = len(matrix)
    m = len(matrix[0])
    a = Array.CreateInstance(float, n, m)
    for i in range(n):
        for j in range(m):
            a[i,j] = matrix[i][j]
    return a


def mult2(matrix1, matrix2):

    N = len(matrix1)
    K = len(matrix2)
    M = len(matrix2[0])

    m1 = ListToArray(matrix1)
    m2 = ListToArray(matrix2)
    res = ListToArray(rand(len(matrix1), len(matrix2[0])))

    watch = Stopwatch()
    print 'mult2 start...'
    watch.Start()
    for i in range(N):
        for j in range(M):
            for k in range(K):
                res[i,j] += m1[i,k]*m2[k,j]
    watch.Stop()
    print 'mult2 ends.'
    print watch.ElapsedMilliseconds
    return res


if __name__ == '__main__':
    #a = rand(280,10304)
    #b = rand(10304,280)

    a = rand(280,10)
    b = rand(10,280)

    c = mult2(a, b)
    d = mult(a, b)

我想尝试两个大矩阵(280 x 10304和10304 x 208),但是两个版本都无法在短时间内产生结果.

然后我尝试了一个小得多的代码(如代码中所示),结果如下:

mult2 : 7902 ms
mult1 : 420 ms

表示在IronPython中使用.NET数组比python List慢得多.

还要注意,C#对这两个大矩阵使用了大约12秒的时间. IronPython已经在小10K倍的情况下花费了很多.我不确定计算机中的IronPython设置是否错误,如果不是,IronPython的数字代码真的很慢.

解决方法:

对于您的特定问题,我认为问题是boxing-在IronPython中,列表项(和所有其他变量)都用盒装存储,因此仅对盒装值进行操作.但是,没有对CLR数组元素进行装箱,因此,IronPython在从数组中提取它们时必须对它们进行装箱,然后在返回途中对它们进行装箱.C#可以对未装箱的值进行操作,并且还有很多其他优化功能使IronPython没有的数组变得更快.

如果您想快速进行数值数学运算,则最好选择NumPy for IronPython.

标签:ironpython,python,net
来源: https://codeday.me/bug/20191208/2090735.html