C ++和C#速度相比 [英] c++ and c# speed compared

查看:192
本文介绍了C ++和C#速度相比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很担心C#的速度时,它重计算,当你需要使用原始CPU处理能力的交易。

I was worried about C#'s speed when it deals with heavy calculations, when you need to use raw CPU power.

我一直认为C ++是比C#快很多当涉及到的计算。所以,我做了一些快速测试。第一个测试计算质数<一个整数n,所述第二测试计算一些pandigital号码。对于第二次测试的想法来自这里: Pandigital号

I always thought that C++ is much faster than C# when it comes to calculations. So I did some quick tests. The first test computes prime numbers < an integer n, the second test computes some pandigital numbers. The idea for second test comes from here: Pandigital Numbers

C#黄金计算:

using System;
using System.Diagnostics;

class Program
{

    static int primes(int n)
    {

        uint i, j;
        int countprimes = 0;

        for (i = 1; i <= n; i++)
        {
            bool isprime = true;

            for (j = 2; j <= Math.Sqrt(i); j++)

                if ((i % j) == 0)
                {
                    isprime = false;
                    break;
                }

            if (isprime) countprimes++;
        }

        return countprimes;
    }



    static void Main(string[] args)
    {
        int n = int.Parse(Console.ReadLine());
        Stopwatch sw = new Stopwatch();

        sw.Start();
        int res = primes(n);
        sw.Stop();
        Console.WriteLine("I found {0} prime numbers between 0 and {1} in {2} msecs.", res, n, sw.ElapsedMilliseconds);
        Console.ReadKey();
    }
}



C ++变种:

C++ variant:

#include <iostream>
#include <ctime>
#include <cmath>

int primes(unsigned long n) {
unsigned long i, j;
int countprimes = 0;
  for(i = 1; i <= n; i++) {
      int isprime = 1;
      for(j = 2; j < sqrt((float)i); j++) 
          if(!(i%j)) {
        isprime = 0;
        break;
   }
    countprimes+= isprime;
  }
  return countprimes;
}

int main() {
 int n, res;
 cin>>n;
 unsigned int start = clock();

 res = primes(n);
 int tprime = clock() - start;
 cout<<"\nI found "<<res<<" prime numbers between 1 and "<<n<<" in "<<tprime<<" msecs.";
 return 0;
}

当我运行测试试图找到素数<超过10万个,C#变体0.409秒完成和C ++0.614秒变种。
当我跑到他们在6.039秒和C ++在大约12.987秒完成百万C#

When I ran the test trying to find primes < than 100,000, C# variant finished in 0.409 seconds and C++ variant in 0.614 seconds. When I ran them for 1,000,000 C# finished in 6.039 seconds and C++ in about 12.987 seconds.

Pandigital测试在C#中:

Pandigital test in C#:

using System;
using System.Diagnostics;

class Program
{
    static bool IsPandigital(int n)
    {
        int digits = 0; int count = 0; int tmp;

        for (; n > 0; n /= 10, ++count)
        {
            if ((tmp = digits) == (digits |= 1 << (n - ((n / 10) * 10) - 1)))
                return false;
        }

        return digits == (1 << count) - 1;
    }

    static void Main()
    {
        int pans = 0;
        Stopwatch sw = new Stopwatch();
        sw.Start();

        for (int i = 1; i <= 123456789; i++)
        {
            if (IsPandigital(i))
            {
                pans++;
            }
        }
        sw.Stop();
        Console.WriteLine("{0}pcs, {1}ms", pans, sw.ElapsedMilliseconds);
        Console.ReadKey();
    }
}



Pandigital测试在C ++:

Pandigital test in C++:

#include <iostream>
#include <ctime>

using namespace std;

int IsPandigital(int n)
    {
        int digits = 0; int count = 0; int tmp;

        for (; n > 0; n /= 10, ++count)
        {
            if ((tmp = digits) == (digits |= 1 << (n - ((n / 10) * 10) - 1)))
                return 0;
        }

        return digits == (1 << count) - 1;
    }


int main() {
   int pans = 0;
   unsigned int start = clock();

   for (int i = 1; i <= 123456789; i++)
   {
      if (IsPandigital(i))
      {
        pans++;
      }
   }
   int ptime = clock() - start;
   cout<<"\nPans:"<<pans<<" time:"<<ptime;  
   return 0;
}



C#的变体,29.906秒运行和C ++在大约36.298秒。

C# variant runs in 29.906 seconds and C++ in about 36.298 seconds.

我没有碰任何编译器开关,C#和C ++程序与调试选项进行了汇编。
之前,我试图运行测试,我很担心C#将远远落在后面的C ++,但现在看来是有在C#中支持一个相当大的速度差。

I didn't touch any compiler switches and both C# and C++ programs were compiled with debug options. Before I attempted to run the test I was worried that C# will lag well behind C++, but now it seems that there is a pretty big speed difference in C# favor.

有人能解释一下吗? C#是即时编译,所以它是正常的一个C ++会比C#变种速度更快C ++编译本地人。

Can anybody explain this? C# is jitted and C++ is compiled native so it's normal that a C++ will be faster than a C# variant.

感谢您的答案!

我重做了发布配置的所有测试。

I've redid all tests for the Release configuration.

第一次测试(质数)

C#(数字< 100,0000):0.189秒
C ++(数字< 100,0000):0.036秒

C# (numbers < 100,0000): 0.189 seconds C++ (numbers < 100,0000): 0.036 seconds

C#(nummbers < 1,000,000):5.300秒
C ++(nummbers< 1,000,000):1.166秒

C# (nummbers < 1,000,000): 5.300 seconds C++ (nummbers < 1,000,000): 1.166 seconds

二测(pandigital号):

Second test (pandigital numbers):

C#:21.224秒
C ++:4.104秒

C#: 21.224 seconds C++: 4.104 seconds

所以,everytthing已经改变,现在C ++的速度要快得多。我的错误是,我已经跑了Debug配置的考验。我可以看到一些速度提升,如果我通过NGEN跑了C#可执行文件?

So, everytthing have changed, now C++ is much faster. My mistake is that I've ran the test for Debug configuration. Can I see some speed improvement if I ran the C# executables through ngen?

我试着比较C#和C ++是因为我知道两者的一些基础知识,我想原因学会处理GUI的API。我在想,WPF是好的,所以因为我针对台式机,我想看看C#可以提供足够的速度和性能,当涉及到使用纯粹的CPU功率来计算各种计算(文件的归档,加密,编解码器等) 。但似乎可悲的是C#不能跟上C ++,当谈到加速。

The reason I tried to compare C# and C++ is because I know some basics of both and I wanted to learn an API dealing with GUI. I was thinking that WPF is nice so given that I'm targeting the desktop, I wanted to see if C# can deliver enough speed and performance when it comes to use sheer CPU power to compute various calculations (file archivers, cryptography, codecs etc). But it seems that sadly C# can't keep pace with C++ when it comes to speed.

所以,我假设我将永远坚持这个问题,<一个HREF =http://stackoverflow.com/questions/2484906/tough-question-on-wpf-win32-mfc>在WPF的Win32,MFC ,我很难回答的问题会新找到一个合适的API

So, I'm assuming I will be forever stuck with this question Tough question on WPF, Win32, MFC, and I'll newer find an suitable API.

推荐答案

为什么你会认为即时编译的代码比本地代码慢?唯一的速度损失将是实际jitting,这只会发生一次(一般来说)。给定一个计划用30秒的运行时间,我们正在谈论的总成本中微不足道的一部分。

Why would you assume that jitted code is slower than native code? The only speed penalty would be the actual jitting, which only happens once (generally speaking). Given a program with a 30-second running time, we are talking about a minuscule portion of the total cost.

我想你可能是混乱的即时编译代码的解释的代码,这被编译线逐线。 。有两间漂亮的显著差异

I think you may be confusing jitted code with interpreted code, which is compiled line-by-line. There's a pretty significant difference between the two.

正如其他人所指出的那样,你还需要在释放模式运行这个;调试模式转弯的关闭的最优化,所以这两个版本将慢于他们应该(但不同的量)。

As others have pointed out, you also need to run this in release mode; debug mode turns off most optimizations, so both versions will be slower than they should be (but by different amounts).

修改 - 我要指出的另一件事情,这是该行:

Edit - I should point out one other thing, which is that this line:

for (j = 2; j <= Math.Sqrt(i); j++)

是令人难以置信的效率低下,可能会与基准干扰。你应该计算的Math.sqrt(我)之外的内部循环。这是可能的,这将通过等量两个版本放缓,但我不知道,不同的编译器将执行不同的优化。

Is incredibly inefficient and may interfere with the benchmarking. You should be calculating Math.Sqrt(i) outside of the inner loop. It's possible that this will slow down both versions by an equivalent amount, but I'm not sure, different compilers will perform different optimizations.

这篇关于C ++和C#速度相比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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