원래이 프로그램을 Java에서 Integer.toBinaryString을 사용하여 작성한 다음 인쇄 결과를 파일에 기록하는 데 사용했습니다. 이 프로그램은 지정된 지수 (이 경우 16 비트)의 모든 2 진 조합을 나열합니다.거의 동일한 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