Thread: trouble to measure time with time.h

  1. #1
    Registered User
    Join Date
    Jul 2006
    Posts
    19

    trouble to measure time with time.h

    hello ebverybody.
    I need to measure the time in some statement and i have the following code to do that
    Code:
    #include <stdio.h>
    #include <time.h>
    int main () {
      clock_t time_before;
      clock_t time_after;
      int i_value=0;
    double tot_time;
    for(i=0; i<N_RUNS; i++)
        {
          i_value++;
        }
      time_after=clock();
      tot_time=((double)(time_after-time_before)/(double)CLOCKS_PER_SEC); /*time in seconds */
      printf("total time %f \n",tot_time);
    The last statement print 0 when i test it. Can somebody tell me what is wrong whith those statement and how should i correct it
    Last edited by Salem; 08-12-2006 at 08:40 AM. Reason: Full flavoured code tags added - use them in future!!!

  2. #2
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,534
    This code will not even compile as-is. Are you sure this is the code you are testing?

    BTW, you should use code tags when posting snippets of code.

    ~/

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Watch the clock on the wall, then look at your processor spec and work out how many instructions it can execute in the time it takes the second hand to move.

    Using clock() is like trying to time a bullet out of a gun using a sun dial.

    You're going to need a much better timer to time short-lived code like that.
    Do a board search for some of my RDTSC examples.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Last edited by Dave_Sinkula; 08-12-2006 at 08:44 AM. Reason: Er... perhaps we should add Salem's stuff to that FAQ.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 12
    Last Post: 02-28-2010, 06:30 AM
  2. Representing floats with color?
    By DrSnuggles in forum C++ Programming
    Replies: 113
    Last Post: 12-30-2008, 09:11 AM
  3. Read and set\change system time
    By Hexxx in forum C++ Programming
    Replies: 9
    Last Post: 01-02-2006, 07:11 AM
  4. I apologize. Good bye.
    By doubleanti in forum A Brief History of Cprogramming.com
    Replies: 14
    Last Post: 05-03-2002, 06:51 PM
  5. relating date....
    By Prakash in forum C Programming
    Replies: 3
    Last Post: 09-19-2001, 09:08 AM