简体   繁体   中英

Timing in C with time.h

I am working on Ubuntu, and I want to time an assembler function in C.

Thats my code:

#include <time.h>
#include <stdio.h>
#include <unistd.h>
extern void assembler_function(char*,int);

int main(){
   char *text1 = "input.txt";
   clock_t start=clock();
   sleep(3); // used for test
   //assembler_function(text1,0);
   clock_t stop=clock();

   //printf("%d %f\n",(int)stop,((float)stop)/CLOCKS_PER_SEC);
   printf("Time : %f \n",(double)start/CLOCKS_PER_SEC);
   printf("Time : %f \n",(double)stop/CLOCKS_PER_SEC);
   printf("Time : %f \n",(double)(stop-start)/CLOCKS_PER_SEC);

   return 0;
}

The results are :

Time : 0.000000

Time : 0.000000

Time : 0.000000

If CLOCKS_PER_SEC is the typical value of 1000000 , it's entirely possible that the range you're measuring is less than one clock (1 microsecond). Also, sleep will not contribute to increases in clock aside from the overhead of the call itself, since clock measures process time, not wall clock time.

Instead, try measuring the time taken to perform multiple calls to the assembler function, then dividing the results by the number of iterations. If the total time to execute the assembler function is very small (eg 1ns) you'll need to be clever about how you do this, otherwise the overhead of the loop could end up being a significant part of the measurement.

Here's a simple example, compiled on a Ubuntu box:

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <sys/time.h>
#include <unistd.h>
#include <time.h>

int64_t timestamp_now (void)
{
    struct timeval tv;
    gettimeofday (&tv, NULL);
    return (int64_t) tv.tv_sec * CLOCKS_PER_SEC + tv.tv_usec;
}

double timestamp_to_seconds (int64_t timestamp)
{
    return timestamp / (double) CLOCKS_PER_SEC;
}

int
main ()
{
    int64_t start = timestamp_now ();
    sleep (1);
    printf ("sleep(1) took %f seconds\n", 
            timestamp_to_seconds (timestamp_now () - start));
    return 0;
}

From the helpful man -page for clock() :

DESCRIPTION

  The clock() function returns an **approximation of processor time used by the program**. 

In other words, clock() is probably not what you want here, because you want to count elapsed wall-clock time, not CPU-usage time (note: sleep() uses almost no CPU time - it just sets an alarm for a wake-up time in the future and then, well, sleeps...).

Use difftime:

First:

time_t t_ini;
t_ini=time(NULL);

At the end:

difftime((int)time(NULL), (int)t_ini);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM