我想制作一个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文件。