Sign in to follow this  
Diton9000

timing is not even

Recommended Posts

I wrote a simple program to learn time.h functions. The program is supposed to generate 0's and 1's for 2 second intervals and report the percentages of each during the interval. However, each 2 second interval takes a different amound of time. Here's the code:
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <fstream>
using namespace std;

int main()
{
    ofstream output;
    output.open("output.txt");
    time_t startTime=0,endTime=0,timeTotal=0;
    int numTimes = 0, randNum = 0;
    double numOnes = 0, numZeros = 0,numNums = 0;
    srand(time(0));
//    time_t offset = 0;
    double percOne = 0, percZero = 0;
    while (true)
    {
        while(timeTotal < 2) //2 is the number of seconds to generate for
        {
            time (&startTime);
            randNum = (rand() % 2);
            if (randNum == 0) 
            {
                numZeros++;
            }
            else if (randNum == 1)
            {
                numOnes++;
            }
            time (&endTime);
            timeTotal += difftime(endTime, startTime);
            startTime = 0;
            endTime = 0;
        }
        while (timeTotal >= 2)
        {
            timeTotal -=2;
        }
        numTimes++;
        numNums = numZeros + numOnes;
//        cout << numNums << endl;
        percZero = (numZeros/numNums) * 100;
        percOne = (numOnes/numNums) * 100;
        
        cout << "Zeros: " << (int)percZero << endl;
        output << percZero << ",";
        cout << "Ones: " << (int)percOne << endl;
        output << percOne << endl;
        numZeros = 0;
        numOnes = 0;
        percZero = 0;
        percOne = 0;
        numNums = 0;
//        system("PAUSE");
    }
    return 0;
}

Share this post


Link to post
Share on other sites
I'd guess the reason is because you're trying to time an extremely short section of code in your program using a very coarse timing function. You assume that the point when the second ticks over is somewhere between calling time(&startTime) and time(&endTime). In reality your program probably spends most of its time in the time() function since that will need a system call (well it would on Linux - I assume Windows works in some kind of similar way), so where the boundary between one second and the next falls will be pretty random. What you want to do instead is something like:


time (&startTime);
while(1)
{
randNum = rand() % 2;
if (randNum == 0)
numZeros++;
else
numOnes++;

time(&endTime);

if (difftime(endTime, startTime) >= 2)
break;
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this