C 关于定时测量的困惑

C 关于定时测量的困惑,c,C,我的任务是实现三个不同的函数:获取当前时间秒1、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

我的任务是实现三个不同的函数:获取当前时间秒1、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;
}
我怎么估计呢?您建议使用哪种定时功能

如果要获得各种定时元素的分辨率(精度),可以使用该函数,传入各种
时钟
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;
}
#包括
#包括
静态无效打印资源(时钟id\u t id)
{
结构timespects;
int rc=时钟(id和ts);
printf(“时钟id:%d\n”,(无符号整数)id);
如果(rc!=0){
printf(“错误:%d\n”,rc);
返回;
}
printf(“tv_sec=%lu\ntv_nsec=%lu\n”,ts.tv_sec,ts.tv_nsec);
}
int main(int argc,字符**argv)
{
printres(时钟实时);
printres(时钟单调);
printres(时钟、进程、CPU时间、ID);
printres(时钟线程CPU时间ID);
返回0;
}
在我的系统上,
tv\u nsec
对于除
CLOCK\u-THREAD\u-CPUTIME\u-ID
以外的所有时钟类型而言是
1000
,对于
CLOCK\u-THREAD\u-CPUTIME\u-ID
而言,
tv\u-nsec
的值是
1
,这意味着其他时钟类型的精度是1毫秒(1000纳秒)而
CLOCK\u THREAD\u CPUTIME\u ID
的精度为1纳秒

对于第一个调用精度的函数,该精度为1秒,因为该函数以秒为单位计算Unix历元的时间

当我必须使用gcc-O0-lrt timing.c-o timing进行编译时,编译器选项-O0-lrt意味着什么

对于某些编译器,如
gcc
clang
,选项
-O
表示在编译到指定级别时优化代码,因此
-O0
表示根本不优化代码,这在调试代码时通常很有用

-l
选项表示根据指定的库进行编译,因此
-lrt
表示使用
rt
库或“实时库”进行编译;这在某些系统上是必要的,因为可以在该库中定义
CLOCK\u REALTIME


我希望这能有所帮助。

您可以通过在一个循环中调用它们并在任何一个结果发生更改时打印它们的所有结果来估计它们的分辨率。