How to display elapsed time in seconds (C program)?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rhen18
    New Member
    • Dec 2009
    • 9

    How to display elapsed time in seconds (C program)?

    i wrote a program w/c requires the user to answer addition drills.
    my problem is i have to display the time it took the user to answer the drills.
    Any codes to suggest?
    Help would be much appreciated!
    Happy new Year!
  • mac11
    Contributor
    • Apr 2007
    • 256

    #2
    You can grab the current time using the function 'time()' (see http://www.cplusplus.com/reference/clibrary/ctime/time/ for reference)

    I'd use it as follows:

    Code:
    time_t start = 0;
    time_t end = 0;
    time_t elapsed = 0;
    
    start = time(NULL);  // grab start time
    // show the question
    
    while(questions_not_done); // do whatever until the questions are all over
    
    end = time(NULL);  // grab the end time
    elapsed = start - end;  // compute elapsed time
    // now show the elapsed time

    Comment

    • Airslash
      New Member
      • Nov 2007
      • 221

      #3
      my trick only works in the Windows Operating system as far as I know, but I always use the ::GetTickCount( ) whenever I need to monitor timeframes between actions.

      This function get's the amount of cpu ticks that have elapsed and can be used to express time intervals in miliseconds whereas time() can only do it till seconds.

      Code:
      #include <windows.h>
      
      // some code
      int start_point = ::GetTickCount();
      // do whatever work here that needs to be monitored
      int elapsed_time = ::GetTickCount() - start_point;

      Comment

      • rhen18
        New Member
        • Dec 2009
        • 9

        #4
        thanks! that worked!
        i modified some things though.
        like i equated elapsed to end - start instead of start - end.
        and i declared the variable elapsed as int because otherwise i get a warning when i compile.
        other than that, it worked! so thanks very much!

        Comment

        • mac11
          Contributor
          • Apr 2007
          • 256

          #5
          end - start instead of start - end.
          Ha ha, what a silly little mistake I made. Good catch!

          Comment

          Working...