How to Calculate Time in C in Linux
When calculating precise time differences in C on the Linux operating system, it's important not to use the popular "clock" function since it only returns the time in seconds, unlike in Windows where it returns in milliseconds. For microsecond and millisecond calculations, you can use the "gettimeofday" function, which works correctly in Linux. You can call the function twice and then use subtraction to calculate the time that has elapsed.
Instructions
-
-
1
Open your C source file in a Linux C editor.
-
2
Include the system time header at the top of your file by adding the code "#include <sys/time.h>." This gives you access to the "gettimeofday" function.
-
-
3
Declare 2 "timeval" structures to store the beginning and end time information by adding the code "struct timeval t_start, t_end;."
-
4
Declare 3 "long" variables to store the seconds, microseconds, and milliseconds of the elapsed time by adding the code "long mil_time, sec_time, usec_time;."
-
5
Call the "gettimeofday" function to get the current time by adding the code "gettimeofday(&t_start, NULL);."
-
6
Call the "gettimeofday" function again after the program has performed other code, by adding the code "gettimeofday(&t_end, NULL);."
-
7
Calculate the elapsed seconds with the code "sec_time = t_end.tv_sec - t_start.tv_sec;", the elapsed microseconds with the code "usec_time = t_end.tv_usec - t_start.tv_usec;" and milliseconds with the code "mil_time = ((1000 * sec_time) + (usec_time/1000.0) + 0.5;." The "0.5" addition is for rounding purposes.
-
8
Save the C source file, compile and run the program.
-
1