C#对C - 大性能差异 [英] C# vs C - Big performance difference

查看:120
本文介绍了C#对C - 大性能差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现用C ANC C#类似code之间巨大的性能差异。

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

在C code是:

#include <stdio.h>
#include <time.h>
#include <math.h>

main()
{
    int i;
    double root;

    clock_t start = clock();
    for (i = 0 ; i <= 100000000; i++){
    	root = sqrt(i);
    }
    printf("Time elapsed: %f\n", ((double)clock() - start) / CLOCKS_PER_SEC);	

}

和C#(控制台应用程序)是:

And the C# (console app) is:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime startTime = DateTime.Now;
            double root;
            for (int i = 0; i <= 100000000; i++)
            {
                root = Math.Sqrt(i);
            }
            TimeSpan runTime = DateTime.Now - startTime;
            Console.WriteLine("Time elapsed: " + Convert.ToString(runTime.TotalMilliseconds/1000));
        }
    }
}

通过上面的code,C#中就完成了0.328125秒(发行版)以及C需要11.14秒运行。

With the above code, the C# completes in 0.328125 seconds (release version) and the C takes 11.14 seconds to run.

的C正在使用的MinGW编译到一个Windows可执行文件。

The c is being compiled to a windows executable using mingw.

我一直在假设的C / C ++是快或至少相当于C#.net下。到底是什么导致C至运行在30倍慢?

I've always been under the assumption that C/C++ were faster or at least comparable to C#.net. What exactly is causing the C to run over 30 times slower?

编辑:
它出现的C#优化器去除根,因为它没有被使用。
我改变了根分配到根+ =和打印出来在最后的总。
我还使用编译的cl.exe与最大速度的/ O2标志设置C

It does appear that the C# optimizer was removing the root as it wasn't being used. I changed the root assignment to root += and printed out the total at the end. I've also compiled the C using cl.exe with the /O2 flag set for max speed.

现在的结果是:
3.75秒为C
2.61秒为C#

The results are now: 3.75 seconds for the C 2.61 seconds for the C#

的C被仍然花费更长的时间,但是这是可接受的

The C is still taking longer, but this is acceptable

推荐答案

既然你从来不使用'根',编译器可能已经删除调用优化方法。

Since you never use 'root', the compiler may have been removing the call to optimize your method.

您可以尝试平方根值积聚成一个累加器,打印出来的方法结束,看看发生了什么事情。

You could try to accumulate the square root values into an accumulator, print it out at the end of the method, and see what's going on.

编辑:看<一个href=\"http://stackoverflow.com/questions/686483/c-vs-c-big-performance-difference/686617#686617\">Jalf's回答下面

这篇关于C#对C - 大性能差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆