You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Debian系Linux下C程序无system()实现高精度时间戳

实现无system()调用的毫秒级时间戳(HH:MM:SS:mmm格式)

嘿,我来帮你搞定这个需求!在Debian系Linux环境下,咱们完全可以抛弃system("date +%H:%M:%S:%N")这种调用外部命令的方式,用C标准库(准确说是POSIX扩展)里的clock_gettime()函数来实现高精度时间戳,而且轻松就能拿到毫秒级精度。

核心思路

clock_gettime()可以获取到纳秒级的系统时间,咱们只需要把纳秒转换成毫秒,再和秒数对应的时分秒格式拼接起来,就能得到你要的HH:MM:SS:mmm格式了。

完整示例代码

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

// 生成HH:MM:SS:mmm格式的时间戳字符串
int get_timestamp(char *buf, size_t buf_size) {
    struct timespec ts;
    // 获取当前系统时间(实时时钟,对应wall-clock时间)
    if (clock_gettime(CLOCK_REALTIME, &ts) != 0) {
        perror("clock_gettime failed");
        return -1;
    }

    struct tm tm_time;
    // 线程安全的本地时间转换,比localtime()更可靠
    if (localtime_r(&ts.tv_sec, &tm_time) == NULL) {
        perror("localtime_r failed");
        return -1;
    }

    // 先格式化HH:MM:SS部分
    int ret = strftime(buf, buf_size, "%H:%M:%S", &tm_time);
    if (ret == 0) {
        fprintf(stderr, "strftime buffer too small\n");
        return -1;
    }

    // 把纳秒转成毫秒,用%03ld确保补零到三位
    long milliseconds = ts.tv_nsec / 1000000;
    ret = snprintf(buf + ret, buf_size - ret, ":%03ld", milliseconds);
    if (ret < 0 || (size_t)ret >= buf_size - ret) {
        fprintf(stderr, "snprintf buffer too small\n");
        return -1;
    }

    return 0;
}

int main() {
    char timestamp[20]; // 足够容纳HH:MM:SS:mmm(最长13字符,留足余量)
    if (get_timestamp(timestamp, sizeof(timestamp)) == 0) {
        printf("%s\n", timestamp);
    }
    return 0;
}

关键细节说明

  • clock_gettime():使用CLOCK_REALTIME时钟,对应系统的墙钟时间,和date命令显示的时间完全一致;如果需要不受系统时间调整影响的单调递增时间,可以换成CLOCK_MONOTONIC。
  • localtime_r():线程安全的时间转换函数,避免了localtime()的线程竞争问题,适合多线程程序。
  • 毫秒格式化:用%03ld可以保证毫秒数不足三位时自动补零(比如5毫秒会显示为005),和你之前用date +%N截取前三位的效果一致。

编译与运行

在Debian/Ubuntu上编译时,直接用gcc即可(现在大多数glibc版本不需要额外链接librt,如果遇到编译错误,加-lrt参数就行):

gcc -o timestamp timestamp.c
# 若出现链接错误,执行下面的命令
gcc -o timestamp timestamp.c -lrt

运行后就能输出类似14:35:22:456的时间戳啦。

内容的提问来源于stack exchange,提问作者muliku

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:53:35