C: gettimeofday() 每次运行都会产生相同的值
我正在尝试以分秒精度打印 ISO-8601 格式的时间。 YYYY-MM-DDThh:mm:ss.s
这是我的代码:
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void milli_time(char* dest, struct timeval* t)
{
struct tm* timeInfo;
strftime(dest, 22, "%Y-%m-%dT%t", localtime(&t->tv_sec));
printf("%s\n", dest);
fflush(stdout);
char deciTime[3];
sprintf(deciTime, ".%lu", ((t->tv_usec)/100000ul));
strcat(dest, deciTime);
}
int main()
{
struct timeval* theTime;
char timeString[32];
gettimeofday(theTime, NULL);
printf("%lu.%lu\n", theTime->tv_sec, theTime->tv_usec);
milli_time(timeString, theTime);
printf("%s\n", timeString);
fflush(stdout);
}
每次运行它时的输出是:
134520616.3077826840
1974-04-06T17:50:16
1974-04-06T17:50:16.30778
我注意到的另一件事是 tv_usec 大于一百万。
I'm trying to print the time in ISO-8601 with decisecond precision.
YYYY-MM-DDThh:mm:ss.s
Here is my code:
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void milli_time(char* dest, struct timeval* t)
{
struct tm* timeInfo;
strftime(dest, 22, "%Y-%m-%dT%t", localtime(&t->tv_sec));
printf("%s\n", dest);
fflush(stdout);
char deciTime[3];
sprintf(deciTime, ".%lu", ((t->tv_usec)/100000ul));
strcat(dest, deciTime);
}
int main()
{
struct timeval* theTime;
char timeString[32];
gettimeofday(theTime, NULL);
printf("%lu.%lu\n", theTime->tv_sec, theTime->tv_usec);
milli_time(timeString, theTime);
printf("%s\n", timeString);
fflush(stdout);
}
And the output every time I run it is:
134520616.3077826840
1974-04-06T17:50:16
1974-04-06T17:50:16.30778
The other thing I notice is that tv_usec is greater than one million.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将 struct timeval* theTime 更改为 struct timeval theTime 并更新对它的相应引用:
这样您就可以为该结构分配空间,而不仅仅是指向该结构的指针结构。当我尝试在我的机器上运行你的代码时出现段错误。
Change
struct timeval* theTime
tostruct timeval theTime
and update the corresponding references to it:This way you're allocating the space for the struct, rather than just a pointer to the struct. Your code segfaults when I try to run it on my machine.