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:
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.
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.
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.
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.
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.
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for