C ++比java慢得多吗? [英] Is C++ so much slower than java?

查看:70
本文介绍了C ++比java慢得多吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在学习Java几年后正在学习C ++,所以我做了几个简单的测试来比较两种语言在每种语言中使用相同代码的工作原理。

我听说过C ++比Java快,但我的代码不是。例如,在您选择的范围内查找素数的程序在C ++中花费20秒,而在Java中花费的时间为76毫秒,范围为50 000.

程序保存素数Vector / ArrayList并确定新数字是否使用它,在两者中都使用相同的算法。



I'm studying C++ after a few years studying Java, so I'm doing several simple test to compare how works each language using the same code in both.
I have ever heard that C++ is faster than Java, but my codes aren't. For example, a program that looks for primes numbers in the range you choose take 20 seconds in C++ against the 76 milliseconds it takes in Java for a range of 50 000.
The programs save the primes in an Vector / ArrayList and determine if the new number is prime using it, exaclty the same algorithm in both.

static boolean comprobarPrimacidad(int n) {
        Iterator<Integer> it = primos.iterator();
        boolean primo = true;
        do {
            if((n%it.next()) == 0) primo = false;
        } while((primo == true) && (it.hasNext()));
        
        if(primo) primos.add(n);
        return primo;}







bool calcularPrimalidad(unsigned int numero) {

	bool primo = true;
	vector<unsigned int>::iterator it = primos.begin();

	do {

		if ((numero % *it) == 0) primo = false;
		it++;
	} while ((it != primos.end()) && primo == true);

	if (primo == false) return false;

	primos.push_back(numero);
	return true;
}





我忘记了什么吗?非常感谢你!

我正在使用Visual Studio 2016 for C ++和Netbeans for Java



我尝试过:



我试图一次又一次地写两个,总是得到相同的结果。在两种情况下,我都在调试器外进行了相同的测试。



Have I forgotten something? Thank you so much!
I'm using Visual Studio 2016 for C++ and Netbeans for Java

What I have tried:

I have tried to write both again and again, always getting the same result. I have done the same test outside the debugger in both case.

推荐答案

我尝试(在我的Lubuntu Box上)以下程序:

I tried (on my Lubuntu Box) the following programs:
import java.util.*;

class Primes
{

  static java.util.ArrayList<Integer> primos;

  static boolean comprobarPrimacidad(int n)
  {
    Iterator<Integer> it = primos.iterator();
    boolean primo = true;
    do
    {
          if((n%it.next()) == 0) primo = false;
    } while((primo == true) && (it.hasNext()));

    if(primo) primos.add(n);
    return primo;
  }


  public static void main( String [] args)
  {
    primos = new java.util.ArrayList<Integer>();

    int n=2;
    primos.add(n);
    while ( primos.size() < 50000)
    {
      ++n;
      comprobarPrimacidad(n);
    }
  }
}







 #include <vector>
 using namespace std;

vector <unsigned int> primos;

bool calcularPrimalidad(unsigned int numero) {

  bool primo = true;
  vector<unsigned int>::iterator it = primos.begin();

  do {

    if ((numero % *it) == 0) primo = false;
    it++;
  } //while ((it != primos.end()) && primo == true);
  while (primo == true && it != primos.end());

  if (primo == false) return false;

  primos.push_back(numero);
  return true;
}


int main()
{
  unsigned int n=2;
  primos.push_back(n);
  while ( primos.size() < 50000)
  {
    ++n;
    calcularPrimalidad(n);
  }

}





执行时间如下:



with the following execution times:

Java    	0m8.573s
C++     	0m25.919s
C++ -O3  	0m4.416s







编译器优化( -O3 for g ++ )显然起主要作用。


你'重新比较苹果和橘子。首先,您编写的用于查找素数的代码天真无效。你没有考虑到任何一种语言幕后发生的事情,你实际上正在发挥两种语言的弱点。



我写的一个实现在VB.NET中,将在2年内在5年的硬件上生成600万个素数。这不是您使用的语言,而是您编写的代码问题。
You're comparing apples to oranges. First, the code you've written to find prime numbers is naively inefficient. You're not taking into account what's going on behind the scenes in either language and you're actually playing to the weaknesses of both languages.

An implementation that I wrote in VB.NET will generate 6 million primes in under 2 seconds on 5 year old hardware. It's not the languages you used, but the code you wrote that's the problem.


性能的这种巨大差异只能通过C ++版本中严重的性能瓶颈来解决。这很可能是由于内存分配的累积,因为阵列一次增加到50,000个元素。在C#版本中,该内存量已预先分配为托管堆。您也可以在C ++中预先分配矢量,如果您知道它可能会变得如此之大,您应该努力这样做。



不要使用 push_back()将矢量增加到50,000!每次添加元素时,都会强制它运行内存分配算法。预先设定矢量或将其初始化为适当的块,一次说500个元素,然后看看你得到了什么结果。
Such an enormous difference in performance can only be accounted for by a serious performance bottleneck in the C++ version. This is most likely caused by an accumulation of memory allocations as the array grows to 50,000 one element at a time. In the C# version, that amount of memory will have been pre-allocated as managed heap. You can pre-allocate the vector in C++ too and you should make the effort to do so if you know it is likely to grow so big.

Don't use push_back() to grow a vector to 50,000! You force it to run the memory allocation algorithm every time you add an element. Presize the vector or initialise it to grow in decent chunks, say 500 elements at a time, and then see what result you get.


这篇关于C ++比java慢得多吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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