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

如何引用setTimer函数中存储的timeElapsed变量在其他函数中做比较

可行解决方案

方案1:修改setTimer返回值,单次调用直接获取

适用场景:仅需要单次获取计时结果,不需要后续持续更新计时值的场景。
修改后的代码实现如下:

// 将原void返回值改为int,返回计算得到的秒级耗时
int setTimer() {
    int timeElapsed = 0;
    time_t beginTimer = time(NULL);
    // 此处保留你原有setTimer内的其他业务逻辑
    timeElapsed = difftime(time(NULL), beginTimer);
    return timeElapsed;
}

// 其他函数调用示例
void otherBusinessFunc() {
    int runTime = setTimer();
    // 直接用返回值做比较判断
    if (runTime > 10) {
        // 超时后的对应业务逻辑
    }
}

方案2:静态局部变量+配套读取函数,受控共享状态

适用场景:需要多次跨函数读取计时值,且setTimer会持续更新timeElapsed的场景,不会引入全局变量污染,变量仅在关联函数内可访问。
代码实现如下:

// 计时读取函数,静态变量作用域仅在当前文件的关联函数内
int getRunningTime() {
    static int timeElapsed = 0;
    static time_t beginTimer = 0;
    // 首次调用时初始化计时起点
    if (beginTimer == 0) {
        beginTimer = time(NULL);
    }
    timeElapsed = difftime(time(NULL), beginTimer);
    return timeElapsed;
}

// 原setTimer函数逻辑保留
void setTimer() {
    // 此处保留你原有setTimer内的其他业务逻辑
    // 调用一次即可更新计时值
    getRunningTime();
}

// 其他函数调用示例
void otherBusinessFunc() {
    int currentTime = getRunningTime();
    if (currentTime > 5) {
        // 对应业务逻辑
    }
}

方案3:封装为计时器结构体,支持多实例独立运行

适用场景:程序中需要同时运行多个独立计时器的场景,是可扩展性最高的实现方式。
代码实现如下:

// 封装计时器所有相关参数,避免变量散落在各个函数中
typedef struct {
    time_t beginTime;
    int elapsedSeconds;
} Timer;

// 初始化新计时器
Timer initTimer() {
    Timer t;
    t.beginTime = time(NULL);
    t.elapsedSeconds = 0;
    return t;
}

// 更新计时器耗时,兼容原有setTimer逻辑
void setTimer(Timer *t) {
    // 此处保留你原有setTimer内的其他业务逻辑
    t->elapsedSeconds = difftime(time(NULL), t->beginTime);
}

// 其他函数调用示例
void otherBusinessFunc(Timer *t) {
    setTimer(t); // 先更新计时值
    if (t->elapsedSeconds > 15) {
        // 对应业务逻辑
    }
}

// 上层使用示例
int main() {
    Timer myTimer = initTimer();
    // 将计时器指针传递到任意需要使用的函数即可
    otherBusinessFunc(&myTimer);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:57:03