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

C语言如何实现程序启动后持续运行、循环中可读取的秒表功能

C语言运行时全局秒表实现方案

原有代码问题汇总

  • 函数名拼写错误:gettimeofday被误写为gettingmeofday,且缺少对应头文件<sys/time.h>
  • 仅读取timeval结构体的tv_usec(微秒字段),该字段最大值仅为999999,每满1秒就会归零,无法累计跨秒的时长
  • 未记录程序启动的基准时间,每次调用仅返回当前时刻的微秒值,无法计算从启动到当前的累计时长
  • 返回值类型为int,当程序运行时间较长时,累计时长会超出int的存储范围,存在溢出风险

正确实现代码

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

// 存储程序启动的基准时间
static long start_sec = 0;
static long start_usec = 0;
static bool is_inited = false;

// 返回从程序启动到当前的累计毫秒数
long gtime() {
    struct timeval now;
    gettimeofday(&now, NULL);
    // 首次调用时初始化基准时间
    if (!is_inited) {
        start_sec = now.tv_sec;
        start_usec = now.tv_usec;
        is_inited = true;
        return 0;
    }
    long delta_sec = now.tv_sec - start_sec;
    long delta_usec = now.tv_usec - start_usec;
    // 处理微秒为负的边界情况
    if (delta_usec < 0) {
        delta_sec--;
        delta_usec += 1000000;
    }
    return delta_sec * 1000 + delta_usec / 1000;
}

void menu() {
    printf("%ld ms\n", gtime());
}

// 测试示例
int main() {
    // 模拟循环中多次调用计时
    for(int i=0; i<5; i++) {
        menu();
        sleep(1);
    }
    return 0;
}

功能说明

  • 程序启动后首次调用gtime()时自动记录基准时间,无需手动初始化
  • 全程计时不会中断,任意时刻调用都能返回从启动到当前的累计时长
  • 可根据需求自行调整返回值精度:
    • 返回微秒:return delta_sec * 1000000 + delta_usec
    • 返回秒:return delta_sec

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 00:54:00