gpt4 book ai didi

C# StringWriter 比 C++ ofstream 更快(通过 pinvoke)?

转载 作者:行者123 更新时间:2023-11-30 19:11:31 25 4
gpt4 key购买 nike

我只是 c++ 的初学者,所以我可能做错了什么,但无论如何我创建了一个 c++ dll 并从我的 wpf 项目中调用它:

C++代码:

extern "C" __declspec (dllexport) double writeTxt()
{
ofstream mf("c:\\cpp.txt");
for(int i=0;i<999;i++)
{
mf<<"xLine: \n";
}
mf.close();
return 1;

}

从 C# 调用代码:

[DllImport(@"C:\Users\neo\Documents\visual studio 2010\Projects\TestDll\Debug\TestDll.dll",
CallingConvention = CallingConvention.Cdecl)]
public static extern double writeTxt();

现在我正在尝试将执行时间与此 c# 函数进行比较:

double writeTxtCs()
{
StreamWriter sw = new StreamWriter(@"c:\cs.txt");
for (int i = 0; i < 999; i++)
{
sw.WriteLine("Line: " + i);
}
sw.Close();
return 0;
}

但是c#函数比c++函数快两倍左右。
像这样测试:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
long[] arr = new long[100];
Stopwatch sw = new Stopwatch();
for (int i = 0; i < 99; i++)
{
sw.Start();
//double xxx = writeTxt();
double xxx = writeTxtCs();
arr[i] = sw.ElapsedMilliseconds;
sw.Reset();
}
MessageBox.Show(arr.Average().ToString());
Close();
}

运行 C# 函数时,我通常需要 ~0.65 毫秒,而运行 C++ 函数时,我通常需要 ~1.1 毫秒。
我的问题是:我是不是做错了什么,或者在这种情况下,c# 真的比 c++ 更快吗?

最佳答案

所有其他答案都有有效点。除了那些:

您正在针对 C++ DLL 的“调试”版本进行测试,这可能会降低 C++ 性能,而不是它对 C# 性能的影响。尝试对两者进行优化,看看效果如何。

尽管如此,I/O 与“语言”并没有太大关系。更多的是关于运行时和操作系统。

关于C# StringWriter 比 C++ ofstream 更快(通过 pinvoke)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11109710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com