C 编程时间和时钟函数

标签 c unix time

我正在开发 Linux 4.4 内核 (Ubuntu),并比较 times 函数(在 sys/times.h 中)和 clock 函数(及时.h)。

根据手册页,times 应该返回程序从某个任意时间开始使用的“CPU 时间”(但该任意时间在函数调用之间应该保持一致)。

此外,根据手册页,clock 应返回程序使用的处理器时间的近似值。

下面的代码使用每个调用来打印完成某些任意工作所需的时间。看起来这些时间应该一致,但它们似乎总是相差一万倍。

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

int main() {
    struct tms times_start, times_end;
    clock_t times_start_retval, times_end_retval;
    clock_t clock_start, clock_end;

    /* clock called first and last, so estimates using "clock" should be
       slightly longer than estimates using "times" */
    if((clock_start = clock()) == -1) {
        perror("starting clock");
        return -1;
    }

    if((times_start_retval = times(&times_start)) == -1) {
        perror("starting times");
        return -1;
    }

    for(int i = 100000000; i; i--); // do work

    if((times_end_retval = times(&times_end)) == -1) {
        perror("ending timer");
        return -1;
    }

    if((clock_end = clock()) == -1) {
        perror("ending clock");
        return -1;
    }

    printf("Times using the clock system call\n");
    printf("clock start: %li\nclock end: %li\n", clock_start, clock_end);
    printf("elapsed: %li\n\n", clock_end - clock_start);

    printf("Times using the times system call\n");
    printf("System start: %li\nUser start: %li, start retval: %li\n",
        times_start.tms_stime, times_start.tms_utime, times_start_retval);
    printf("System end:   %li\nUser end:   %li, end retval:   %li\n",
        times_end.tms_stime, times_end.tms_utime, times_end_retval);
    printf("elapsed: %li\n\n", times_end_retval - times_start_retval);

    return 0;
}

结果是:

Times using the clock system call
clock start: 5016
clock end: 321323
elapsed: 316307

Times using the times system call
System start: 0
User start: 0, start retval: 1733759140
System end:   0
User end:   31, end retval:   1733759172
elapsed: 32

根据描述,这些似乎应该同时返回。事实上,它们不是,这让我想知道潜在的可移植性问题。为什么这些时间不同?

最佳答案

也许我只是想问这个问题。我想我刚刚在Linux 编程接口(interface)(Kerrisk 2011,第 206-207 页)中找到了答案。答案似乎是“CPU 时间”以两种不同的方式测量。

times 返回以“时钟滴答”为单位测量的时间。每秒的时钟滴答数可以使用sysconf(_SC_CLK_TCK)检索对于我的系统来说是 100。所以每个时钟周期大约是 1/100 秒。

clock 返回以“每秒时钟数”为单位测量的时间。显然,对于 Unix 兼容系统,该值应始终为 1,000,000。当我从 time.h 头文件中打印 CLOCKS_PER_SEC 时,这就是我在系统上得到的结果。

要获得秒数,我必须除 clock返回值除以 1,000,000,或除 times返回值除 100。这意味着每个“时钟滴答”有 10,000 个“时钟”。这似乎解释了我看到的 10,000 差异的原因。

关于C 编程时间和时钟函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53686500/

相关文章:

linux - curl - 在 shell 脚本内运行特殊字符 URL 时出现问题

python - 有没有办法在不暂停整个程序的情况下模拟 time.sleep() 函数的效果?

c - 为什么GCC使用mov/mfence而不是xchg来实现C11的atomic_store?

c++ - 将所有库保存在 Arduino 草图目录中

C 统一码 : How do I apply C11 standard amendment DR488 fix to C11 standard function c16rtomb()?

c - ncurses 形式 : Show editing cursor/highlight active field

linux - 使用 Bash 创建用户

linux - 在循环内调用 sftp 脚本时循环退出

python - 添加两个小时的python

c - 时间测量、CPU 滴答声和可调节的 CPU 频率?