Why is .NET faster than C++ in this case?

后端 未结 13 1486
长发绾君心
长发绾君心 2021-02-02 00:59

Make sure you run outside of the IDE. That is key.

-edit- I LOVE SLaks comment. \"The amount of misinformation in these answers is staggering.\" :D

13条回答
  •  春和景丽
    2021-02-02 01:43

    EDIT: While the original C++ timing is wrong (comparing cycles to milliseconds), better timing does show C# is faster with vanilla compiler settings.

    OK, enough random speculation, time for some science. After getting weird results with existing C++ code, I just tried running:

    int fib(int n)
    {
        if (n < 2) return n;
        return fib(n - 1) + fib(n - 2);
    }
    
    int main()
    {
        __int64 time = 0xFFFFFFFF;
        while (1)
        {
            int n;
            //cin >> n;
            n = 41;
            if (n < 0) break;
            LARGE_INTEGER start, end, delta, freq;
            ::QueryPerformanceFrequency( &freq );
            ::QueryPerformanceCounter( &start );
            int res = fib(n);
            ::QueryPerformanceCounter( &end );
            delta.QuadPart = end.QuadPart - start.QuadPart;
            cout << res << endl;
            cout << ( delta.QuadPart * 1000 ) / freq.QuadPart <

    EDIT:

    MSN pointed out you should time C# outside the debugger, so I re-ran everything:

    Best Results (VC2008, running release build from commandline, no special options enabled)

    • C++ Original Code - 10239
    • C++ QPF - 3427
    • C# - 2166 (was 4700 in debugger).

    The original C++ code (with rdtsc) wasn't returning milliseconds, just a factor of reported clock cycles, so comparing directly to StopWatch() results is invalid. The original timing code is just wrong.

    Note StopWatch() uses QueryPerformance* calls: http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx

    So in this case C++ is faster than C#. It depends on your compiler settings - see MSN's answer.

提交回复
热议问题