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

为何C语言sleep(5)后clock()计算的执行时长不是5秒?

问题:clock()统计sleep(5)时长远小于预期的原因

我期望以下C语言代码输出的程序执行时长约为5秒,代码通过clock()记录起始与结束时间,中间调用sleep(5)模拟耗时操作,但实际输出的执行时长仅约0.000047秒,恳请解释原因。

代码示例

#include <stdio.h>
#include <time.h>
#include <unistd.h>
 
int main() {
    clock_t start, end;

    /* Store start time here */
    start = clock();
    
    /* Do 5 seconds of work */
    sleep(5);

    /* program logic ends here */
    end = clock();

    printf("start: %f\n", (double)start);
    printf("end: %f\n", (double)end);
    
    /* Get the time taken by program to execute in seconds */
    double duration = ((double)end - start)/CLOCKS_PER_SEC;
     
    printf("duration: %f, CPS: %li\n", duration, CLOCKS_PER_SEC);

    printf("Time taken to execute in seconds : %f\n", duration);
    return 0;
}

实际输出

start: 1097.000000
end: 1144.000000
duration: 0.000047, CPS: 1000000
Time taken to execute in seconds : 0.000047

原因解释

clock()函数统计的是进程实际占用CPU的时间,而非从程序启动到结束的真实流逝时间(墙上时钟时间)。

当调用sleep(5)时,当前进程会被操作系统挂起,这段时间内进程完全不占用CPU资源,clock()自然不会统计这段时间。你看到的0.000047秒,只是程序执行clock()调用、printf()输出等代码时实际消耗的CPU时间,和sleep()的5秒无关联。

正确计时方案

如果需要统计真实流逝时间,可以使用以下几种方法:

  • time()函数:精度到秒
    time_t start = time(NULL);
    sleep(5);
    time_t end = time(NULL);
    double duration = difftime(end, start);
    
  • clock_gettime()函数:POSIX标准,精度可达纳秒
    struct timespec start, end;
    clock_gettime(CLOCK_MONOTONIC, &start);
    sleep(5);
    clock_gettime(CLOCK_MONOTONIC, &end);
    double duration = (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec)/1e9;
    
  • gettimeofday()函数:精度到微秒
    struct timeval start, end;
    gettimeofday(&start, NULL);
    sleep(5);
    gettimeofday(&end, NULL);
    double duration = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec)/1e6;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 09:05:11