I’m just a beginner at c++ so I might be doing something wrong but anyways I created a c++ dll and I call it from my wpf project:
c++ code:
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;
}
calling code from c#:
[DllImport(@"C:\Users\neo\Documents\visual studio 2010\Projects\TestDll\Debug\TestDll.dll",
CallingConvention = CallingConvention.Cdecl)]
public static extern double writeTxt();
Now I’m trying to compare the execution time with this c# function:
double writeTxtCs()
{
StreamWriter sw = new StreamWriter(@"c:\cs.txt");
for (int i = 0; i < 999; i++)
{
sw.WriteLine("Line: " + i);
}
sw.Close();
return 0;
}
but the c# function is about twice as faster than the c++ function.
tested like this:
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();
}
When running the c# function I normally get ~0.65ms and when running the c++ function I get ~1.1ms.
my question is: am I doing something wrong or does c# really is faster in this scenario than c++?
All other answers have valid points. In addition to those:
You are testing against “Debug” build of your C++ DLL and that might be degrading C++ performance more than how it affects C#’s performance. Try unleashing optimizations on both and see how it works out for you.
Nevertheless I/O doesn’t have much to do with the “language”. It’s more about runtime and the OS.