any way to store number ... from gettimeofday() and ... without using any array?
gettimeofday()
does not return the "number of time ticks". It is a *nix
functions defined to populate a struct timeval
which contains a time_t
and a long
representing the current time in seconds and microseconds. Use clock()
to get "number of time ticks".
The simplest way to avoid an array is to keep the result in a struct timeval
without any modifications.
This will save memory for each instance of a program which calculates current time.
This sounds like OP would like to conserve memory as much as possible. Code could convert the struct timeval
to a int64_t
(a count of microseconds since the epoch) without much risk of range loss. This would only be a memory savings if sizeof(struct timeval) > sizeof(int64_t)
.
#include <sys/time.h>
int64_t timeval_to_int64(const struct timeval *tv) {
const int32_t us_per_s = 1000000;
int64_t t = tv->tv_sec;
if (t >= INT64_MAX / us_per_s
&& (t > INT64_MAX / us_per_s || tv->tv_usec > INT64_MAX % us_per_s)) {
// Handle overflow
return INT64_MAX;
}
if (t <= INT64_MIN / us_per_s
&& (t < INT64_MIN / us_per_s || tv->tv_usec < INT64_MIN % us_per_s)) {
// Handle underflow
return INT64_MIN;
}
return t * us_per_s + tv->tv_usec;
}
void int64_to_timeval(struct timeval *tv, int64_t t) {
const int32_t us_per_s = 1000000;
tv->tv_sec = t / us_per_s;
tv->tv_usec = t % us_per_s;
if (tv->tv_usec < 0) { // insure tv_usec member is positive.
tv->tv_usec += us_per_s;
tv->tv_sec++;
}
}
If code wants to save the timestamp to a file as text, with minimal space, a number of choices are available. What is the most efficient binary to text encoding?
goes over some ideas. For OP's code though a decimal or hexadecimal print of the 2 members may be sufficient.
printf("%lld.%06ld\n", (long long) tv.tv_sec, tv.tv_usec);
I do not recommend storing timestamps via localtime()
as that imparts ambiguity or overhead of timezone and day light savings time. If code must saving using month, day, year, consider ISO 8601 and using universal time.
#include <sys/time.h>
int print_timeval_to_ISO8601(const struct timeval *tv) {
struct tm t = *gmtime(&tv->tv_sec);
return printf("%04d-%02d-%02dT%02d:%02d:%02d.%06ld\n", //
t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, //
t.tm_hour, t.tm_min, t.tm_sec, tv->tv_usec);
// Or ("%04d%02d%02d%02d%02d%02d.%06ld\n"
}
Note OP's code has a weakness. Microsecond values like 12 will print a ".12"
when ".000012"
should appear.
// printf("%s%ld\n",buffer,tv.tv_usec);
printf("%s%06ld\n",buffer,tv.tv_usec);