C ++程序运行速度比几乎相同的Java程序慢得多

时间:2017-02-08 09:28:15

标签: java c++

我最初使用Integer.toBinaryString在Java中编写此程序,然后使用printwriter将结果写入文件。该程序列出了指定指数中的所有二进制组合(在本例中为16位)。

package binary;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;


public class BINARY {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    try (PrintWriter myFile = new PrintWriter("myThing.txt")) {
        for (int i = 0; i < Math.pow(2, 16); i++) { // Iterates over 16 bits
            myFile.println(Integer.toBinaryString(i));
        }
        myFile.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(BINARY.class.getName()).log(Level.SEVERE, null, ex); // standard execption handler added by NetBeans IDE

    }

}

}

用C ++编写的程序以类似的方式编写,但使用cin&lt;&lt; n,其中n是提升到基数2的幂,因为C ++需要编译,因此添加接口可以更快地进行测试(没有cin&lt;&lt; n;构造,性能非常相似)。

#include <iostream>
#include <fstream>
#include <bitset>
#include <string>
#include <cmath>

using namespace std;

int binary(int n) {
    int remainder, binaryNumber = 0, i = 1, step = 1;
    while (n != 0)
    {
        remainder = n % 2;
        //cout << "Step " << step++ << ": " << n << "/2, Remainder = " << remainder << ", Quotient = " << n / 2 << endl;
        n /= 2;
        binaryNumber += remainder*i;
        i *= 10;
    }
    return binaryNumber;
}

int main()
{
    int n;
    cout << "Enter the number of bits" << endl;
    cin >> n;
    cin.ignore();
    ofstream myFile;
    myFile.open("output64.txt");
    cout << "Listing all bit combinations. This may take a while. Please wait." << endl;
    for (int i = 0; i < pow(2, n); i++)
    {
        myFile << binary(i) << "\n";
        cout << "Number of iterations = " << i << endl;
    }
    myFile.close();
}

Java中的程序通常在不到一秒的时间内完成16位。但是,C ++需要几秒钟(10-15)来处理所有二进制数字。这似乎没有意义,因为C ++不需要虚拟机来运行字节码,并且直接编译成机器代码,或者至少是操作系统的目标代码解释为机器代码,所以它应该更快,如果有的话。任何人都有可能的解释? std :: bitset&lt;&gt;()也被预先使用并以类似的方式运行,性能明智。我尝试省略二进制转换器并用cout替换myFile,但性能没有改变。仍然约为5000次迭代/秒。

1 个答案:

答案 0 :(得分:-1)

主要问题是输入数据IO,与c ++计算器速度无关。尝试将这两部分分开:IO +计算。并有一个ClockWatch变量用于计算开始/结束时间。