首页 > 解决方案 > 对时序测量的困惑

问题描述

我的任务是实现三个不同的函数 get_current_time_seconds1、2 和 3,然后必须估计各种函数的分辨率。我如何估计这个?

您建议使用哪个计时功能?当我必须使用 gcc -O0 -lrt timing.c -o timing 编译时,编译器选项 -O0 -lrt 是什么意思?

#define BILLION 1000000000L

#define LIMIT_I 1000
#define LIMIT_J 1000

double get_current_time_seconds1()
{
    /* Get current time using gettimeofday */
    time_t t = time(NULL);
    struct tm *tm = localtime(&t);
    printf("%s\n", asctime(tm));
    return (double) tm;
}

double get_current_time_seconds2()
{
    struct timespec start,stop;
    clock_gettime(CLOCK_REALTIME, &start);
    clock_gettime(CLOCK_REALTIME, &stop);
    double x = (stop.tv_sec - start.tv_sec) + (stop.tv_nsec - start.tv_nsec);

    printf("%lf\n", x);

    return (double) x;
}

double get_current_time_seconds3()
{
    uint64_t diff;

    struct timespec start, end;

    clock_gettime(CLOCK_MONOTONIC, &start);
    sleep(5);
    clock_gettime(CLOCK_MONOTONIC, &end);

    diff = BILLION * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec;
    printf("elapsed time = %llu nanoseconds\n", (long long unsigned int)diff);

    return (double) diff;
}

标签: c

解决方案


我如何估计这个?您建议使用哪个计时功能?

如果要获取各种计时元素的分辨率(精度),可以使用clock_getres函数,传入各种CLOCK_id类型,例如:

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

static void printres(clockid_t id)
{
    struct timespec ts;
    int rc = clock_getres(id, &ts);
    printf("clock id: %d\n", (unsigned int)id);
    if (rc != 0) {
        printf("Error: %d\n", rc);
        return;
    }
    printf("tv_sec = %lu\ntv_nsec = %lu\n", ts.tv_sec, ts.tv_nsec);
}

int main(int argc, char** argv)
{
    printres(CLOCK_REALTIME);
    printres(CLOCK_MONOTONIC);
    printres(CLOCK_PROCESS_CPUTIME_ID);
    printres(CLOCK_THREAD_CPUTIME_ID);
    return 0;
}

在我的系统上,tv_nsec除了CLOCK_THREAD_CPUTIME_IDis之外1000,对于isCLOCK_THREAD_CPUTIME_ID的值,这意味着其他时钟类型的精度为 1 毫秒(1000 纳秒),而 的精度为 1 纳秒。tv_nsec1CLOCK_THREAD_CPUTIME_ID

对于调用localtime精度的第一个函数,该函数将计算 Unix 纪元的时间(以秒为单位)。

当我必须使用 gcc -O0 -lrt timing.c -o timing 编译时,编译器选项 -O0 -lrt 是什么意思?

对于某些编译器,gccclang选项-O意味着在将代码编译到指定级别时优化代码,因此-O0意味着根本不优化代码,这在调试代码时通常很有用。

-l选项表示针对指定的库-lrt进行编译,因此表示使用该rt库或“实时库”进行编译;这在某些系统上是必需的,CLOCK_REALTIME可以在该库中定义。

我希望这能有所帮助。


推荐阅读