Solved

Problem timing a function in C

Posted on 2007-11-27
15
177 Views
Last Modified: 2010-04-15
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

0
Comment
Question by:jonathanjeffrey
  • 7
  • 2
  • 2
  • +3
15 Comments
 
LVL 13

Expert Comment

by:josgood
ID: 20363381
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
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 20363440
where do you initialize the 'before' variable?

it should be:
      clock_t before = clock();
0
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 20363452
also elapsed is not initialized, should be:
    double elapsed = 0.0;
0
 
LVL 13

Expert Comment

by:josgood
ID: 20363483
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
 
LVL 84

Expert Comment

by:ozo
ID: 20363516
can you try
elapsed = elapsed + (((double)clock()-before)/CLOCKS_PER_SEC);
0
 

Author Comment

by:jonathanjeffrey
ID: 20363600
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
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 20363615
why to refuse to initialize the clock_t values?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:jonathanjeffrey
ID: 20363646
I"ve tried that as well and get the exact same result.
0
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 20363662
printf("Total Time So Far: %f\n", 1, (elapsed));
       
should be

printf("Total Time So Far: %i, %f\n", 1, (elapsed));
       
0
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 20363663
also you have declared 'goal' twice.
0
 
LVL 55

Accepted Solution

by:
Jaime Olivares earned 400 total points
ID: 20363668
indeed should be just:
printf("Total Time So Far: %f\n", elapsed);
       
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 20363827
>> 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
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 20363849
the printf problem is all !!!
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 20363854
>> the printf problem is all !!!

The other two I mentioned (and ozo and you before me) are problems too ;)
0
 
LVL 22

Assisted Solution

by:grg99
grg99 earned 100 total points
ID: 20365041
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

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now