带时钟的性能计时

时间:2019-02-22 15:00:32

标签: c

E

我必须使用当前称为get_current_time_seconds3()的当前方法更改get_seconds(),然后检查观察时间的方式之间的差异。然后,通过这两个函数中的哪一个似乎最适合于Casche性能分析。

我不太确定如何处理此问题。谁能指导我?

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

#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()
{
    /*struct sysinfo info;
    sysinfo(&info);

    const time_t boottime = time(NULL) - info.uptime;
    struct timespec monotime;
    clock_gettime(CLOCK_MONOTONIC, &monotime);
    time_t curtime = boottime + monotime.tv_sec;

    printf("Current time = %s", ctime(&curtime));*/

    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;
}

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;
}

0 个答案:

没有答案