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

标签 c# performance visual-c++ dll pinvoke

我只是 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/

相关文章:

C++ 'class' 类型重定义错误

c# - 检查射线是否击中立方体

c# - 如何从Style.Triggers升级到Interaction.Behaviors?

templates - Web 开发人员的项目模板目录

android - 每当我尝试运行我的 Flutter 程序时,它都会卡在 “Running Gradle task ' assembleDebug”

c++ - 在 Visual Studio 2012 中链接 zlib

c# - 在 Roslyn 中编辑循环

c# - WCF 双工中的 TPL 数据流 block

c# - 通过索引更新 List<T> 中的元素是否应该比使用 ArrayList 索引更快?

windows - 如何将 Visual Studio 的 “Output” 窗口重定向到 DebugView?