Posts

Showing posts with the label C

Avoid using comparison operators on time_t

As specific in  http://www.cplusplus.com/reference/ctime/time_t/ , the time_t may be implemented using alternative time representations by libraries. Just because time_t is arithmetic, that doesn't mean it stores time as monotone increasing values for advancing time. It can be different in different systems. Although most of linux distros do store it as integer but it is no harm to be careful. The time.h header file provides us difftime function just for calculating the different by seconds between two  time_t variables. Some may worry about the overhead of the function over a simple subtract expression. Well, in some architectures, it's implemented as a macro. For example, POSIX,  http://man7.org/linux/man-pages/man3/difftime.3.html So, the right way to compare 2 time_t values, a, b should be: if (difftime(b, a) > 0) //... If you check for a time duration is passed or not, do something like, time_t now = time(NULL); if (difftime(now, a) >= duration) ...

Measure time execution in a C program

There are many ways to measure time in a C program. I use  clock_gettime () since it supports high resolution clock which we can count on. Header #include <time.h> Time storage structure struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; Function int clock_gettime ( clockid_t clk_id, struct timespec *tp); is used to retrieve the time of the specified clock clk_id. There are several kind of clock ID but the two of them may be used the most. CLOCK_REALTIME : System-wide clock that measures real (i.e., wall-clock) time. CLOCK_MONOTONIC : Clock that cannot be set and represents monotonic time since some unspecified starting point. On Linux, that point corresponds to the number of seconds that the system has been running since it was booted. Below is an example of using the function. #include <stdio.h> #include <time.h> struct timespec time_subtract ( struct timespec t...