Counter (Time)

This is a discussion on Counter (Time) within the C Programming forums, part of the General Programming Boards category; Hi, I am writing a program that will ask simple maths questions to build up better mental aritmatic etc. I ...

  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    12

    Counter (Time)

    Hi,

    I am writing a program that will ask simple maths questions to build up better mental aritmatic etc.
    I need a way of timing how long it takes to answer a set of say 20 questions so that i could combine that with a percentage to get some sort of feel for improvement each time it is run.

    Any ideas

    Thanks in advanced.

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I'm guessing that 20 questions of non-trivial answers will take a fair bit more than 20 seconds, so 1 second resolution is probably sufficient, in which case the standard time() and difftime() functions should be sufficient. (1 second out of 20 seconds is 5% error - if it's longer than 20 seconds, it gets better).

    If 1 second resolution is not good enough, then you would need to use non-standard time functions, and which ones you have available depends on the OS you are writing your application for.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Feb 2009
    Posts
    138
    sample.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main()
    {
        int val;
        time_t x;
        printf("enter a number> ");
        x = time(NULL);
        scanf("%d", &val);
        printf("it took %d seconds to type %d\n", (int)difftime(time(NULL), x), val);
        return EXIT_SUCCESS;
    }
    it's the same idea for your program, just with more stuff in between.

  4. #4
    Registered User
    Join Date
    Feb 2009
    Posts
    12
    sorry, but i cant see when that time starts counting? It cant count from when program starts incase user wants to have more than one go without closing down the program.
    Using googled knowledge on difftime only i have 'guessed' how to code it, does any of this seem to be on the right track?


    Code:
    time_t_t1 = time(NULL)
    
    		 /** user answers questions **/
    
    time_t_t2 = time(NULL);
    diff = difftime(time_t_t1, time_t_t2);
    
    
    printf("%d\n", diff);

  5. #5
    Registered User
    Join Date
    Feb 2009
    Posts
    138
    it starts counting at "x = time(NULL);". the "counter" is actually a two part process of measuring the current time in one place, then measuring it again later on and comparing the difference of those two times to find out how long it was between them.

  6. #6
    Registered User
    Join Date
    Feb 2009
    Posts
    12
    right i see, i was looking for a x1 and x2 value, but one you just calculate inside the difftime which is much simpler!


    Although I seem to understand it, i cant seem to get it to work! Apparantly it takes me 0 seconds when testing it.

    Below is my reduced code, at the moment only asking 2 questions as it became quite tedious to test it 20 times!

    Code:
    time_t_t1 = time(NULL);
    	for(i=0;i<2;i++){
    
    		/** for loop each time asking new question**/
    	}
    	
    	perc = (200 / j);
    	printf("Congratulations! You have answered 2 answers correctly out of %d.\n", j);
    	printf("Your results are,\nPercentage: %d%%\n", perc);
    	printf("%d\n", difftime(time_t_t1, time(NULL)));

    Any idea what i have missed?
    Thanks

  7. #7
    Registered User
    Join Date
    Feb 2009
    Posts
    138
    difftime returns a double, and printf is fickle about types. you need to cast the result of difftime to int if you want to print a %d. also the idea is that difftime is a fancy way of saying arg1-arg2 where arg1 and arg2 are the arguments to difftime. the later time should be the first argument and the earlier time the second or the result will be wrong.
    Code:
    printf("%d\n", (int)difftime(time(NULL), time_t_t1));

  8. #8
    Registered User
    Join Date
    Feb 2009
    Posts
    12
    Ok cheers all working now!

    It would be nicer to have a higher accuracy on time measurements, but as first poster said you would struggle to read, calculate and type answer anywhere near to 1 second per question.

    Thanks all

  9. #9
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,604
    There is clock(), which I believe, is standard.
    Otherwise you must tell us the OS, and we can give you example of functions to use.
    If you really need them, of course.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    Registered User
    Join Date
    Feb 2009
    Posts
    138
    Quote Originally Posted by Elysia
    There is clock(), which I believe, is standard.
    except you don't know what the resolution is. you can get the number of clock ticks in a second but a tick isn't defined.

  11. #11
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,604
    True, but I am pretty sure it would at least allow for an interval of 100ms or so. It sucks, but it's the price you pay for portability.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    Reading this I get curious to know how this is dealt with normally when you really need precision, or need to clock short timing intervals.
    Last edited by Subsonics; 02-10-2009 at 10:15 AM.

  13. #13
    Registered User
    Join Date
    Feb 2009
    Posts
    138
    Quote Originally Posted by Subsonics
    Reading this I get curious to know how this is dealt with normally when you really need precision, or need to clock short timing intervals.
    there are functions the system provides like GetTickCount that give a higher resolution. they don't work everywhere though. GetTickCount only works on windows boxes, and that's the portability problem Elysia mentioned.

  14. #14
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by Elysia View Post
    There is clock(), which I believe, is standard.
    Otherwise you must tell us the OS, and we can give you example of functions to use.
    If you really need them, of course.
    clock() is indeed standard. However, by the definition in the C Standard, it does not give you "wall-clock time", but the amount of time used by the CPU. That is not particularly useful for measuring how long the user takes to answer questions - since 99.999% of that time will be spent waiting for the user to type in "24" as the answer to "what's 5 * 5 - 1" - a modern CPU can do a billion instructions in one second, and it probably doesn't take more than a few thousand or so to produce the output and start waiting for the user input. So it's unlikely that 20 questions even amounts to one clock-tick.

    [Of course, in Windows, you don't get CPU time, you get wall-clock time - but that's ONLY in Windows and DOS - because it was that way in DOS!].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  15. #15
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    This is the most accurate timing code I've seen for Windows:

    Code:
    /****************\
    **  SetupTiming  *************************************************\
    **                                                              **
    **    SetupTiming increases the waits for 1 second for other    **
    **    tasks to finish, and increases the priority of the        **
    **    solver.  Since we are using a high preformace timers,     **
    **    these steps help make the timing more accurate and        **
    **    repeatable (there is still some variation from run to     **
    **    run, but much less than if we don't do this).             **
    **                                                              **
    **    Note: under Windows, doing this really does make the      **
    **          timings more consistant. Under Linux, there does    **
    **          not appear to be anything I can do to improve       **
    **          the consistancy of the timings.  The timings        **
    **          appear to change by 10% or more between runs.       **
    **                                                              **
    \****************************************************************/
    void SetupTiming (void)
    {
      // Only do this for Windows, it does not seem to help under Linux
      #ifdef WIN32
        // Get the frequency of the timer (for my system, it was a 0.279 usec a tick)
        QueryPerformanceFrequency (&Frequency);
    
        // If puzzle timing, wait 1 second before running the puzzle to allow
        //   other background threads to finish up.  This provides better timings
        if (timing_mode) 
        {
          GETTIME (StartTime);
          do { GETTIME (EndTime); }
          while ((EndTime.QuadPart - StartTime.QuadPart) < Frequency.QuadPart);
        } 
    
        // To make the timing more accurate, raise the priority of the program.
        //   This helps prevent other things from inturrupting the solving. 
        SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
        SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
      #endif
    }
    
    
    #ifdef WIN32
      #include <windows.h>           // Allow high preformance timing routines
    #else
      #include <time.h>              // Allow high preformance timing routines 
      #include <stdlib.h>            // For exit()
    #endif
    #include <stdio.h>   
    
    // For timing, use the high preformance windows timers
    #ifdef WIN32
      LARGE_INTEGER Frequency, StartTime, EndTime, SolveTime;
      #define GETTIME(x) QueryPerformanceCounter (&x)
    #endif
    
    if (timing_mode == 2) 
          GETTIME (StartTime);               // Get the current timer for puzzle timing
    
        PuzSolCnt = Solver(num_search, use_subsets, buffer);  // Solve the puzzle
    
        if (timing_mode == 2)  
          GETTIME (EndTime);                 // Get ending time if timing puzzles
        if (double_check) DoubleCheck();     // Verify the solution
        SolvedCnt += PuzSolCnt;              // Update solved count
        DisplaySolution();                   // Display the solution and timing
      }
    
      GETTIME (EndTime);                     // Get ending timer
      DisplayTiming();   
    
    
    void DisplayTiming (void)
    {
      float  fulltime;         
    
      #ifdef WIN32
          fulltime = (float)(EndTime.QuadPart - StartTime.QuadPart) / float)Frequency.QuadPart;
        
      if (fulltime > 0.95)
         printf ("  Time = %3.3f sec   ", fulltime);
      else if (fulltime > 0.00095)
         printf ("  Time = %3.3f msec  ", fulltime * 1000);
      else 
         printf ("  Time = %3.3f usec  ", fulltime * 1000000);
      }
    Although the author of the above notes that Windows 32 bit has a bug in it's timing routines that sometimes reports negative times, I've seen this report very fine timing resolutions. Getting the frequency of the system is key, I'm sure.

    It gets confusing because the author has various timing modes, and code, spread out across the file.

    Hopefully, the above disparate bits of code will give you some clues, however.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Using pointers
    By Big_0_72 in forum C Programming
    Replies: 3
    Last Post: 10-28-2008, 07:51 PM
  2. Sending an email in C program
    By Moony in forum C Programming
    Replies: 28
    Last Post: 10-19-2006, 10:42 AM
  3. The new FAQ
    By Hammer in forum A Brief History of Cprogramming.com
    Replies: 34
    Last Post: 08-30-2006, 10:05 AM
  4. calculating user time and time elapsed
    By Neildadon in forum C++ Programming
    Replies: 0
    Last Post: 02-10-2003, 05:00 PM
  5. time class
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 12-11-2001, 09:12 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21