【问题标题】:C: gettimeofday() produces the same value every runC: gettimeofday() 每次运行都会产生相同的值
【发布时间】:2011-11-20 06:57:02
【问题描述】:

我正在尝试以分秒精度打印 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 大于一百万。

【问题讨论】:

    标签: c time gettimeofday


    【解决方案1】:

    struct timeval* theTime 更改为struct timeval theTime 并更新对它的相应引用:

    gettimeofday(&theTime, NULL);
    // etc
    

    这样您就可以为结构分配空间,而不仅仅是指向结构的指针。当我尝试在我的机器上运行时,您的代码会出现段错误。

    【讨论】:

      猜你喜欢
      • 2012-05-02
      • 2012-03-16
      • 1970-01-01
      • 2016-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      相关资源
      最近更新 更多