-3

I originally wrote this program in Java using the Integer.toBinaryString and then used printwriter to write the results to a file. This program lists all binary combinations in the specified exponent (in this case, 16 bits).

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

    }

}

}

The program written in C++ is written in much of a similar way, but with a cin << n, where n is the power being raised to the base 2, as C++ requires compilation, so adding an interface allows quicker testing (without the cin << n; construct, performance is very similar).

#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();
}

The program in Java is completes 16 bits in less than a second, usually. However, C++ requires several seconds (10-15) to process all of the binary digits. This doesn't seem to make sense as C++ doesn't need a virtual machine to run bytecode, and is compiled straight into machine code, or at least object code for the operating system to interpret into machine code, so it should be faster, if anything. Anyone have a possible explanation? std::bitset<>() was also used beforehand and acted in a similar way, performance wise. I tried omitting the binary converter and replaced myFile with cout, but the performance doesn't change. Still about ~5000 iterations/sec.

Jack Raiden
  • 23
  • 1
  • 7
  • Compilation options, optimisation level? – Richard Critten Feb 08 '17 at 09:29
  • 7
    These do not seem to be doing the same thing at all. – chrylis -cautiouslyoptimistic- Feb 08 '17 at 09:30
  • See this http://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio – samgak Feb 08 '17 at 09:36
  • 1
    You are converting the number into an integer whose decimal representation is the same as your original binary. This is going to get stuck pretty fast for wide binary number, and requires lots of multiplications and divisions. You should be converting to an array of chars, as the Java original does. Have you considered looking at the source of the `Integer` class in Java to see how they do it? – RealSkeptic Feb 08 '17 at 09:36
  • Does the time taken for the C++ include the `pow(2, n)` calls to `cout << ...` -- each with a flush due to `endl`? You really need to make sure you're comparing like with like. – G.M. Feb 08 '17 at 09:37
  • endl - the most abused of all things in std – UKMonkey Feb 08 '17 at 09:38
  • 1
    Can you show us please how *exactly* do you mesure time? – Yuriy Ivaskevych Feb 08 '17 at 09:41
  • 1
    And why `binary` returns integer ? If you try to calculate numbers consisting of 16 bits (as you do in Java) then your `binary` would (is supposed to at least) return an integer number consisting of 16 digits, which is actually far more than `int` can hold (up to 2^31 -1 which is only 10 digits in length) and cause *Undefined Behaviour*. – Yuriy Ivaskevych Feb 08 '17 at 09:45
  • The `binary` function crashes if n is greater than or equal to 1024 – macroland Feb 08 '17 at 09:48
  • These aren't "almost identical" - `binary` doesn't do anything even similar to what `Integer.toBinaryString` does. – molbdnilo Feb 08 '17 at 10:05
  • @molbdnilo I also tried std:bitset<>(). Doesn't that do a similar thing, but with a static number of bits? – Jack Raiden Feb 08 '17 at 10:12
  • @JackRaiden You never mentioned what compiler options you used to build the program. If you're running an unoptimized, i.e. "debug" build, your findings are meaningless. Second, don't use `pow` and integer exponents. Not only is it slower calling it every time your `for` loop iterates, it is not guaranteed to give you the correct answers [as this question shows](http://stackoverflow.com/questions/25678481/why-does-pown-2-return-24-when-n-5-with-my-compiler-and-os) – PaulMcKenzie Feb 08 '17 at 11:31

1 Answers1

-1

The main problem is with input data IO, not related to c++ calculator speed. Try to separate those two part: IO + calculation. And have a ClockWatch variable for counting start/end time.