是否有任何方法可以在不使用任何数组的情况下存储 gettimeofday() 中的时间刻度数并将其格式化为某种特定方式(例如“%m-%d-%Y %T”)?
这将为计算当前时间的程序的每个实例节省内存。
使用数组进行相同的代码。(取自 C - gettimeofday for computing time? )
char buffer[30];
struct timeval tv;
time_t curtime;
gettimeofday(&tv, NULL);
curtime=tv.tv_sec;
strftime(buffer,30,"%m-%d-%Y %T.",localtime(&curtime));
printf("%s%ld\n",buffer,tv.tv_usec);
any way to store number ... from gettimeofday() and ... without using any array?
gettimeofday()
不返回“时间刻度数”。它是一个 *nix
函数,定义为填充 struct timeval
,其中包含一个 time_t
和一个表示当前时间的 dài
时间以秒和微秒为单位。使用clock()
获取“时间刻度数”。
避免使用数组的最简单方法是将结果保存在 struct timeval
中而不进行任何修改。
This will save memory for each instance of a program which calculates current time.
这听起来像 OP 希望尽可能节省内存。代码可以将 struct timeval 转换为 int64_t (自纪元以来的微秒计数),而不会产生太大的范围丢失风险。仅当 sizeof(struct timeval) > sizeof(int64_t)
时,这才会节省内存。
#include
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++;
}
}
如果代码想要将时间戳作为文本保存到文件中,并且空间最小,可以有多种选择。 What is the most efficient binary to text encoding?回顾一些想法。对于 OP 的代码,尽管 2 个成员的十进制或十六进制打印可能就足够了。
printf("%lld.%06ld\n", (long long) tv.tv_sec, tv.tv_usec);
我不建议通过 localtime()
存储时间戳,因为这会导致时区和夏令时的模糊性或开销。如果代码必须使用月、日、年保存,请考虑 ISO 8601并使用世界时间。
#include
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"
}
注意OP的代码有一个弱点。当出现 ".000012"
时,像 12 这样的微秒值将打印 ".12"
。
// printf("%s%ld\n",buffer,tv.tv_usec);
printf("%s%06ld\n",buffer,tv.tv_usec);
Tôi là một lập trình viên xuất sắc, rất giỏi!