私はもともとInteger.toBinaryStringを使ってこのプログラムをJavaで書いた後、プリントライターを使って結果をファイルに書き出しました。このプログラムは、指定された指数(この場合は16ビット)内のすべてのバイナリの組み合わせをリストします。ほとんど同じJavaプログラムよりもはるかに遅いC++プログラム
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++で書かれたプログラムは、同様の多くで書かれているが、nがベース2に昇温されている電力であるCIN < < Nと、C++コンパイルを必要としますインターフェイスを追加することで、より速いテストが可能になります(cinなしで、< < 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のプログラムは、通常1秒未満で16ビットで完了します。しかし、C++は2進数のすべてを処理するには数秒(10-15)必要です。これは、C++がバイトコードを実行する仮想マシンを必要とせず、マシンコードに直接コンパイルされているか、少なくともオペレーティングシステムのオブジェクトコードが機械コードに変換されるので意味がないようです。したがって、もしあれば。誰でも可能な説明がありますか? std :: bitset <>()もあらかじめ使用され、同様の方法でパフォーマンスが向上しました。バイナリコンバータを省略し、myFileをcoutに置き換えましたが、パフォーマンスは変わりません。まだ〜約5000回/秒です。
コンパイルオプション、最適化レベル? –
これらは全く同じことをしているようには見えません。 – chrylis
を参照してください。http://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio – samgak