2

E

I have to change the get_seconds() with my current method called get_current_time_seconds3() and by then check the observation in difference between ways of measuring time. And by that see which of these two functions seems best suited for casche peformance analysis.

I'm not quite sure how to handle this problem. Can anyone please guide me?

#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;
}
David
  • 667
  • 4
  • 18

0 Answers0