C# code:
using System;
using System.Diagnostics;
class Program {
static void Main() {
int n = 100000000;
int x = 0;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < n; i++) {
x += i;
}
stopwatch.Stop();
Console.WriteLine("Time elapsed: {0} ms", stopwatch.Elapsed.TotalMilliseconds);
Console.WriteLine("Result: {0}", x);
}
}
C++ code:
#include <iostream>
#include <chrono>
int main()
{
int n = 100000000;
int x = 0;
auto start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < n; i++)
{
x += i;
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "Time elapsed: " << duration.count() << " ms" << std::endl;
std::cout << "Result: " << x << std::endl;
return 0;
}
C# gives me results around 230 ms while C++ constantly gives me time 260+ ms.
I tried few other examples but always in such simple loop examples C# seems to beat C++..
Could someone explain me how it happens? Thoguht that C# has no chance to reach C++ performance..
Thank you in advance for help <3
3