python - 为什么 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 文件。
解决方案
推荐阅读
- mongodb - 带有 MongoDB sink 连接的 Confluent Cloud 无法正常工作
- c - 可以在 Xlib 中使用原始 RGB 作为颜色吗?
- javascript - React 中的多个按键
- security - Knox SSO 与 Keycloak 错误的集成 - 缺少必需的主题
- service-accounts - GCP:无法通过 gcloud/API 创建项目接收器
- mysql - 如何在连接的子查询中使用主列值
- apache-spark - 如何从函数参数动态创建列
- ruby-on-rails - 在 ruby 中使用正则表达式验证密码时出错
- java - Selenium 浏览器配置文件使用默认用户详细信息而不是使用传递的凭据登录到 SSO
- python - 如何处理数据集中的多种日期时间格式?