首页 > 解决方案 > 为什么 Python 中的方法比使用相同 dll 的 C# 中的方法慢?

问题描述

我想制作一个python代码,但它需要大量的计算。我认为编写一些基于 c# 的方法并从 python 调用 dll 会很好。为了测试,我写了一些简单的代码(见下文)。以下是 C# 中的示例代码:


    namespace TestFrameWork
    {
        public class Class1
        {
            public static float Summ(float[][] arr, int rowsHeight, int colsWidth)
            {
                float value = 0;
                for (int col = 0; col < colsWidth; col++)
                {
                    for (int row = 0; row < rowsHeight; row++)
                    {
                        value += 1;
                    }
                }
                return value;
            }
        }
    }

和测试:


    namespace main
    {
        class Program
        {

            static void Main(string[] args)
            {

                float[][] inputs = Enumerable
                       .Range(0, 4000)               
                       .Select(i => new float[33000])  
                       .ToArray();                 

                var watch = System.Diagnostics.Stopwatch.StartNew();
                var result = Class1.Summ(inputs, 4000, 33000);
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Console.WriteLine(result);
                Console.WriteLine($"Elapsed time: {elapsedMs} ms");
            }
        }
    }

以及从 Python 加载方法的代码:

import numpy as np
import clr
import time

w = 4000
h = 33000
image  = np.ones((h,w))
clr.AddReference(r"C:\Users\nagym\source\repos\TestFrameWork\bin\Debug\TestFrameWork.dll")
from TestFrameWork import Class1
image1 = image.data.tolist()
start = time.time()
result = Class1.Summ(image1,w,h)
print(f"Elapsed time c# : {(time.time() - start)*1000} ms")

结果:

VS C#  ->  Elapsed time:       318 ms
Python ->  Elapsed time c# : 24567.59548187256 ms

使用 Visual Studio 运行 C# 代码要快得多。但为什么?我正在使用相同的 DLL 文件。

标签: pythonc#performancedllclr

解决方案


推荐阅读