格式化struct timespec

时间:2011-11-29 00:24:32

标签: c linux gcc

如何将struct timespec格式化为字符串?该结构例如返回在Linux gcc上的clock_gettime()

struct timespec {
    time_t   tv_sec;        /* seconds */
    long     tv_nsec;       /* nanoseconds */
};

5 个答案:

答案 0 :(得分:39)

格式化的一种方法是:

printf("%lld.%.9ld", (long long)ts.tv_sec, ts.tv_nsec)

答案 1 :(得分:15)

我想问同样的问题。这是我目前获得这样一个字符串的解决方案:2013-02-07 09:24:40.749355372 我不确定是否有比这更简单的解决方案,但至少字符串格式可以通过这种方法自由配置。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define NANO 1000000000L

// buf needs to store 30 characters
int timespec2str(char *buf, uint len, struct timespec *ts) {
    int ret;
    struct tm t;

    tzset();
    if (localtime_r(&(ts->tv_sec), &t) == NULL)
        return 1;

    ret = strftime(buf, len, "%F %T", &t);
    if (ret == 0)
        return 2;
    len -= ret - 1;

    ret = snprintf(&buf[strlen(buf)], len, ".%09ld", ts->tv_nsec);
    if (ret >= len)
        return 3;

    return 0;
}

int main(int argc, char **argv) {
    clockid_t clk_id = CLOCK_REALTIME;
    const uint TIME_FMT = strlen("2012-12-31 12:59:59.123456789") + 1;
    char timestr[TIME_FMT];

    struct timespec ts, res;
    clock_getres(clk_id, &res);
    clock_gettime(clk_id, &ts);

    if (timespec2str(timestr, sizeof(timestr), &ts) != 0) {
        printf("timespec2str failed!\n");
        return EXIT_FAILURE;
    } else {
        unsigned long resol = res.tv_sec * NANO + res.tv_nsec;
        printf("CLOCK_REALTIME: res=%ld ns, time=%s\n", resol, timestr);
        return EXIT_SUCCESS;
    }
}

输出:

gcc mwe.c -lrt 
$ ./a.out 
CLOCK_REALTIME: res=1 ns, time=2013-02-07 13:41:17.994326501

答案 2 :(得分:3)

以下将返回符合 ISO8601 和 RFC3339 的 UTC 时间戳,包括纳秒。

它使用 strftime(),它与 struct timespec 一起使用与 struct timeval 一样好,因为它只关心秒数,两者都提供。然后附加纳秒(注意用零填充!)以及 UTC 后缀“Z”。

示例输出:2021-01-19T04:50:01.435561072Z

#include <stdio.h>
#include <time.h>
#include <sys/time.h>

int utc_system_timestamp(char[]);

int main(void) {
    char buf[31];
    utc_system_timestamp(buf);
    printf("%s\n", buf);
}

// Allocate exactly 31 bytes for buf
int utc_system_timestamp(char buf[]) {
    const int bufsize = 31;
    const int tmpsize = 21;
    struct timespec now;
    struct tm tm;
    int retval = clock_gettime(CLOCK_REALTIME, &now);
    gmtime_r(&now.tv_sec, &tm);
    strftime(buf, tmpsize, "%Y-%m-%dT%H:%M:%S.", &tm);
    sprintf(buf + tmpsize -1, "%09luZ", now.tv_nsec);
    return retval;
}

GCC 命令行示例(注意 -lrt):

gcc foo.c -o foo -lrt

答案 3 :(得分:1)

您可以将tv_sec参数传递给某些格式化函数。看看gmtime,localtime()。然后看看snprintf。

答案 4 :(得分:-11)

你可以使用std :: stringstream。您可以将任何内容流入其中:

std::stringstream stream;
stream << 5.7;
stream << foo.bar;

std::string s = stream.str();

这应该是一种非常通用的方法。 (仅适用于C ++,但您也问过这种语言的问题。)