1

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

4 Answers 4

1

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 (e.g. 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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

While correct, the lack of explanation limits the educational value. It is not clear why this solution is better. It could be improved by identifying what the problem was (the lack of resolution in clock, as well as its functions suitability -- user-time versus wall-clock time) and how this resolves those problems.
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...).

Comments

0

Use difftime:

First:

time_t t_ini; t_ini=time(NULL); 

At the end:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.