C# vs C - Big performance difference

前端 未结 13 593
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 01:39

I\'m finding massive performance differences between similar code in C anc C#.

The C code is:

#include 
#include 
#inclu         


        
13条回答
  •  执笔经年
    2020-11-28 02:43

    I put together (based on your code) two more comparable tests in C and C#. These two write a smaller array using the modulus operator for indexing (it adds a little overhead, but hey, we're trying to compare performance [at a crude level]).

    C code:

    #include 
    #include 
    #include 
    #include 
    
    void main()
    {
        int count = (int)1e8;
        int subcount = 1000;
        double* roots = (double*)malloc(sizeof(double) * subcount);
        clock_t start = clock();
        for (int i = 0 ; i < count; i++)
        {
            roots[i % subcount] = sqrt((double)i);
        }
        clock_t end = clock();
        double length = ((double)end - start) / CLOCKS_PER_SEC;
        printf("Time elapsed: %f\n", length);
    }
    

    In C#:

    using System;
    
    namespace CsPerfTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                int count = (int)1e8;
                int subcount = 1000;
                double[] roots = new double[subcount];
                DateTime startTime = DateTime.Now;
                for (int i = 0; i < count; i++)
                {
                    roots[i % subcount] = Math.Sqrt(i);
                }
                TimeSpan runTime = DateTime.Now - startTime;
                Console.WriteLine("Time elapsed: " + Convert.ToString(runTime.TotalMilliseconds / 1000));
            }
        }
    }
    

    These tests write data to an array (so the .NET runtime shouldn't be allowed to cull the sqrt op) although the array is significantly smaller (didn't want to use excessive memory). I compiled these in release config and run them from inside a console window (instead of starting through VS).

    On my computer the C# program varies between 6.2 and 6.9 seconds, while the C version varies between 6.9 and 7.1.

提交回复
热议问题