Problem timing a function in C

So in my code below I loop doing:

1) create some data (the exact same data is created every time), and put it into a double array.
2) record clock time
3) process the data
4) calculate the elapsed time, and add it to the elapsed total
5) print out the running total

The first 50 or so times through the loop the elapsed time prints out as 0.0000000.....
Then all of a sudden it jumps to:
19991590273549713308756725058274066432.000000
and stays there for the remainder of the 100 iterations, even though all 100 of the iterations take the same amount of time (or at least with a very small degree of variation).  

Can anybody tell me what is up with this?  I'm trying to get an average for how long the function takes to run.

Thanks

int main()
{
    int i = 0;
    int numIterations = 100;
    double elapsed;
    clock_t before;
    //complexData is a double []    
 
    while(i < numIterations)
    {
        createSomeData(complexData, SIZE);
        before = clock();
        processData(complexData-1, SIZE, 1);
        elapsed = elapsed + ((clock()-before)/CLOCKS_PER_SEC);
        printf("Time: %f\n", 1, (elapsed));
        i++;
    }
        printf("Avg Time: %.6f\n", 1, (elapsed)/(double)numIterations);
    return 0;
}

Open in new window

jonathanjeffreyAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Jaime OlivaresConnect With a Mentor Software ArchitectCommented:
indeed should be just:
printf("Total Time So Far: %f\n", elapsed);
       
0
 
josgoodCommented:
Your code looks good and an approximation of it works for me with VS2005 and Windows.

I suggest trying an experiment:
1)  Add a sleep function, such as
     #include <time.h>
 
     void sleep(unsigned int mseconds)
     {
         clock_t goal = mseconds + clock();
         while (goal > clock());
     }
2)  Comment out the body of your two functions.  Insert a call to sleep(100), replacing the commented-out function bodies.
3)  Run the program again.  Do you still have the problem?
0
 
Jaime OlivaresSoftware ArchitectCommented:
where do you initialize the 'before' variable?

it should be:
      clock_t before = clock();
0
The Firewall Audit Checklist

Preparing for a firewall audit today is almost impossible.
AlgoSec, together with some of the largest global organizations and auditors, has created a checklist to follow when preparing for your firewall audit. Simplify risk mitigation while staying compliant all of the time!

 
Jaime OlivaresSoftware ArchitectCommented:
also elapsed is not initialized, should be:
    double elapsed = 0.0;
0
 
josgoodCommented:
jaime,
>>> it should be:       clock_t before = clock();
True, but he initializes it before he uses it, so that can't be the problem

>>> elapsed is not initialized, should be:     double elapsed = 0.0;
True, but his first 50 results are 0.0, so I assume he's running in debug and it has been initialized for him

I don't see that either of these issues (which *do* need to be fixed) are the issue at hand.

Joe
0
 
ozoCommented:
can you try
elapsed = elapsed + (((double)clock()-before)/CLOCKS_PER_SEC);
0
 
jonathanjeffreyAuthor Commented:
When I do as you suggested (with the sleep) here is what I get:

Total Time So Far: 19991590273549713308756725058274066432.000000
Total Time So Far: 19991590273549713308756725058274066432.000000
Total Time So Far: -867922223097221370168116877201515784922139248644532267208898808839557630748696704099662268797170773829846843370648123698126302700889669906793665517821708629455610365972120963375935430768976082294358492129001472.000000
Total Time So Far: 19991590273549713308756725058274066432.000000
Total Time So Far: -0.000000


With the code below.  

Whats going on!?
int main()
{
    int i = 0;
    int numIterations = 5;
    double elapsed = 0.0;
    clock_t before;
    clock_t goal;
       while(i < numIterations)
      {
        before = clock();
        clock_t goal = 100 + clock();
        while(goal > clock())
          {
          }
        elapsed = elapsed + (((double)clock()-
                            (double)before)/CLOCKS_PER_SEC);
        printf("Total Time So Far: %f\n", 1, (elapsed));
        i++;
      }
     return 0;
}

Open in new window

0
 
Jaime OlivaresSoftware ArchitectCommented:
why to refuse to initialize the clock_t values?
0
 
jonathanjeffreyAuthor Commented:
I"ve tried that as well and get the exact same result.
0
 
Jaime OlivaresSoftware ArchitectCommented:
printf("Total Time So Far: %f\n", 1, (elapsed));
       
should be

printf("Total Time So Far: %i, %f\n", 1, (elapsed));
       
0
 
Jaime OlivaresSoftware ArchitectCommented:
also you have declared 'goal' twice.
0
 
Infinity08Commented:
>> can you try
>> elapsed = elapsed + (((double)clock()-before)/CLOCKS_PER_SEC);

Did you check ozo's post ?

That's pretty sure to be the problem, since your original code was doing integer division, and you want it to do double division. I would do this however :

        elapsed += ((double) (clock() - before)) / CLOCKS_PER_SEC;

You also need to initialize elapsed to 0 of course as jaime_olivares suggested :

        elapsed = 0.0

And the printf statement needs to be fixed as jaime_olivares also said :

        printf("Time: %f\n", elapsed);
0
 
Jaime OlivaresSoftware ArchitectCommented:
the printf problem is all !!!
0
 
Infinity08Commented:
>> the printf problem is all !!!

The other two I mentioned (and ozo and you before me) are problems too ;)
0
 
grg99Connect With a Mentor Commented:
What's happening is you have an extra "1," in the printf list.  This causes printf to try to print out as a double the value  of an integer "1" in the lower 32 bits followed by the lower 32 bits of the elapsed time as the upper 32 bits of a double.   So you're going to see huge random-looking numbers.

You see printf has no way at run-time or compile time to check for type-compatibility of the %format specifiers versus the actual parameters.  This is exacerbated by C's silent promotion of all parameters to ints and doubles.

Another problem is that your clock() function on your computer probably has a granularity of many milliseconds.   Depending on the time spent in the timed function you might have to bump up the loop repetition count so that clock()'s granularity is not so noticeable.

Also keep in mind that repeating a block of code with the same input data is a misleading way to time code.  Most computers have code and data caches so when you repeat code and data it may run *many* times faster than it will in a real life situation.

0
All Courses

From novice to tech pro — start learning today.