Search code examples
c++precisionostream

ostream double precision


So I've implemented my own array data structure. I've implemented operations such as:

  1. Adding an element on a specified index
  2. Removing an element --------||--------
  3. Checking if the value exists in array

Now I have to measure the time for these operations. I've got this code: (im using Visual Studio C++)

LARGE_INTEGER clock, start, end, result;
QueryPerformanceFrequency(&clock);
int sizes[] = { 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000 };
long double seconds;
long double summedSeconds = 0;
std::ofstream myfile;
myfile.open("results.txt");
std::setprecision(10); //I want the precision to be 1ns + 1 bit for rounding
for (auto&x : sizes)
{
    for (int i = 0 ; i < 100; i++)
    {                   
        myArray.generate(x); // this generates myArray of size x
        QueryPerformanceCounter(&start);
        myArray.insert(1, x / 2); //this will insert value of 1 into an index = half of array
        QueryPerformanceCounter(&end);
        result.QuadPart = end.QuadPart - start.QuadPart;
        seconds = (long double)result.QuadPart / (long double)clock.QuadPart;
        summedSeconds += seconds; // this is summed up for 100 example data                 
    }
    std::cout << summedSeconds/100 << '\n';

    myfile << std::fixed << std::setw(6) << x << "\t" << summedSeconds/100 << '\n';
}
myfile.close();

Now, this gives me something like this in results.txt:

   100  0.000008
   200  0.000013
   500  0.000031
  1000  0.000052
  2000  0.000115
  5000  0.000287
 10000  0.000568
 20000  0.001134
 50000  0.002017
100000  0.003756

So based on the number of elements, the time is measured. But the lecturer wants ~1ns precision, so that's not enough (now it's only 6 bits, I want at least 9-10). When I wasn't already saving it to a file, I was couting that information using std::fixed and std::cout.precision(10). And it worked as I wanted. How can I make it work for saving to a file?

P.S I unfortunately cannot use boost::


Solution

  • The same manipulators that you've used with cout can be used with fstreams without any problems. Try using the same code you've used when printing to standard output.