How to Calculate Time Difference in C++

Written by marty simmons
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Calculate Time Difference in C++
C++ has time difference functions as part of the standard library. (ANSI image by DBX 60 from Fotolia.com)

In any programming language, being able to find the time and the difference between two recorded times is important in many situations. Whether you are calculating frames-per-second for a video game, recording the time between inputs or trying to benchmark your software, C++ has built-in standard libraries for measuring time. All you need to do is include the appropriate libraries, add the time functions to your program and make a few calculations. No special third party libraries are needed.

Skill level:
Easy

Other People Are Reading

Instructions

  1. 1

    Include the C++ time library in your program with the line "#include <time.h>" at the top of the program with any other include statements.

  2. 2

    Declare two time objects in your main program loop. You can create time objects with code similar to "time_t anytime, othertime;". Replace "anytime" and "othertime" with your preferred variable names. You also need to declare a variable of the double type to store the time difference value.

  3. 3

    Assign values to the two time objects within your program. When and where will depend on why you need to calculate the time difference. Give the variables a value using the time function. For example, the code "time (&anytime);" would call the time function and store the result in the time object "anytime" from Step 2.

  4. 4

    Use the "difftime" function using your two time objects as the input and assign the result to your difference variable. Call the function with code similar to "timedif = difftime(endtime,starttime);" where "timedif" is your difference value.

  5. 5

    Utilise your data however you see fit. With the time difference stored in a variable, you are free to manipulate and use it within your program.

Don't Miss

Filter:
  • All types
  • Articles
  • Slideshows
  • Videos
Sort:
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the eHow.co.uk site, you consent to the use of cookies. For more information, please see our Cookie policy.