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 (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.
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);
Related
I am using clock function for my c program to print execution time of current program.I am getting wrong time in output.I want to display time in seconds,milliseconds and microseconds.
#include <stdio.h>
#include <unistd.h>
#include <time.h>
int main()
{
clock_t start = clock();
sleep(3);
clock_t end = clock();
double time_taken = (double)(end - start)/CLOCKS_PER_SEC; // in seconds
printf("time program took %f seconds to execute \n", time_taken);
return 0;
}
time ./time
time program took 0.081000 seconds to execute
real 0m3.002s
user 0m0.000s
sys 0m0.002s
I expect output around 3 seconds however it display wrong.
As you see if I run this program using Linux command time I am getting correct time,I want to display same time using my c program.
Contrary to popular belief, the clock() function retrieves CPU time, not elapsed clock time as the name confusingly may induce people to believe.
Here is the language from the C Standard:
7.27.2.1 The clock function
Synopsis
#include <time.h>
clock_t clock(void);
Description
The clock function determines the processor time used.
Returns
The clock function returns the implementation’s best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation. To determine the time in seconds, the value returned by the clock function should be divided by the value of the macro CLOCKS_PER_SEC. If the processor time used is not available, the function returns the value (clock_t)(−1). If the value cannot be represented, the function returns an unspecified value.
To retrieve the elapsed time, you should use one of the following:
the time() function with a resolution of 1 second
the timespec_get() function which may be more precise, but might not be available on all systems
the gettimeofday() system call available on linux systems
the clock_gettime() function.
See What specifically are wall-clock-time, user-cpu-time, and system-cpu-time in UNIX? for more information on this subject.
Here is a modified version using gettimeoday():
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
int main() {
struct timeval start, end;
gettimeofday(&start, NULL);
sleep(3);
gettimeofday(&end, NULL);
double time_taken = end.tv_sec + end.tv_usec / 1e6 -
start.tv_sec - start.tv_usec / 1e6; // in seconds
printf("time program took %f seconds to execute\n", time_taken);
return 0;
}
Output:
time program took 3.005133 seconds to execute
I'm trying to measure time it takes to run a command using my own command interpreter, but is the time correct? When I run a command it says time much longer than expected:
miniShell>> pwd
/home/dac/.clion11/system/cmake/generated/c0a6fa89/c0a6fa89/Debug
Execution time 1828 ms
I'm using the gettimeofday as can be seen from the code. Isn't it wrong somewhere and should be changed so that the timing looks reasonable?
If I make a minimal example, then it looks and runs like this:
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
int main(int argc, char *argv[]) {
long time;
struct timeval time_start;
struct timeval time_end;
gettimeofday(&time_start, NULL);
printf("run program>> ");
gettimeofday(&time_end, NULL);
time = (time_end.tv_sec-time_start.tv_sec)*1000000 + time_end.tv_usec-time_start.tv_usec;
printf("Execution time %ld ms\n", time); /*Print out the execution time*/
return (0);
}
Then I run it
/home/dac/.clion11/system/cmake/generated/c0a6fa89/c0a6fa89/Debug/oslab
run program>> Execution time 14 ms
Process finished with exit code 0
The above 14 ms seems reasonable, why is the time so long for my command?
The tv_usec in struct timeval is a time in microseconds, not milliseconds.
You compute the time incorrectly. tv_usec, where the u stands for the Greek lowercase letter μ ("mu"), holds a number of microseconds. Fix the formula this way:
gettimeofday(&time_end, NULL);
time = (((time_end.tv_sec - time_start.tv_sec) * 1000000LL) +
time_end.tv_usec - time_start.tv_usec) / 1000;
printf("Execution time %ld ms\n", time); /* Print out the execution time*/
It is preferable to make the computation in 64 bits to avoid overflows if long is 32 bits and the elapsed time can exceed 40 minutes.
If you want to preserve the maximum precision, keep the computation in microseconds and print the number of milliseconds with a decimal point:
gettimeofday(&time_end, NULL);
time = (time_end.tv_sec - time_start.tv_sec) * 1000000 +
time_end.tv_usec - time_start.tv_usec;
printf("Execution time %ld.%03ld ms\n", time / 1000, time % 1000);
Sorry I am new to C. But what am I doing wrong? Tried almost everything, but still can not calculate seconds passed to execute the code between t1 and t2, always returns me
Finished in 0.00 seconds.
Thanks for your patience :)
#include <time.h>
clock_t t1, t2;
t1 = clock();
sleep(5);
t2 = clock();
printf("\nFinished in %.2f seconds.\n\n", (t2-t1)*1.0/CLOCKS_PER_SEC);
If coarse granularity (whole second) is ok, perhaps time(2) and time_t are good enough.
Example:
#include <stdio.h>
#include <time.h>
#include <unistd.h>
static time_t t1, t2;
int
main(void)
{
t1 = time(0);
(void) sleep(5);
t2 = time(0);
(void) printf("\nFinished in %d seconds.\n\n", (int) (t2-t1));
return 0;
}
It seems like clock_t does not take input account the "wall time", but CPU time.
The CPU is not effectively executing the code when it sleeps for 5 seconds.
clock() is unsuitable for measuring elapsed time. It's resolution is generally very low and it only measures CPU time, not wall time. If you're targeting Unix you should use clock_gettime(CLOCK_MONOTONIC, ...). On Windows QueryPerformanceCounter() is the API to use.
It is worth noting that gettimeofday() is also unsuitable because it is affected by leap seconds and adjustments by the network time protocol.
I am checking process duration with C code.
It works in Windows 32 bits environment, but not in Linux 64bits.
At least my process takes longer than 3 minutes, but it shows 0.062 sec.
My code is below.
#include <stdio.h>
#include <time.h>
#include <Windows.h>
int main(void)
{
clock_t start = clock();
//....... doing something. Sorry:D
printf("%.3f sec\n", (double)(clock() - start) / CLOCKS_PER_SEC);
return 0;
}
How to fixed this code to work in 64bits Linux also?
Thanks.
The function clock(3) doesn't yield the elapsed time:
The value returned is the CPU time used so far as a clock_t.
As the simplest example, if your process sleeps or block for I/O, it won't use much CPU time. If you need to measure actual duration, you could use time(3) and difftime(3) or maybe clock_gettime and the like.
Side note: I don't really understand why the code appears to work in Windows, but changing to time + difftime should work on both platforms.
Why not use the time command to get the various time measurements?
I begin learn about the Linux C,but i meet the problem so confused me.
I use the function times.but return the value equals 0.
ok i made the mistak,I changed the code:
But the is not much relative with printf. clock_t is define with long in Linux.so i convert clock_t to long.
This is my code:
#include <sys/times.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
long clock_times;
struct tms begintime;
sleep(5);
if((clock_times=times(&begintime))==-1)
perror("get times error");
else
{
printf("%ld\n",(long)begintime.tms_utime);
printf("%ld\n",(long)begintime.tms_stime);
printf("%ld\n",(long)begintime.tms_cutime);
printf("%ld\n",(long)begintime.tms_cstime);
}
return 0;
}
the output:
0
0
0
0
the also return 0;
and I using gdb to debug,Also the variable of begintimes also to be zero.
there is no relative with printf function.
Please
This is not unusual; the process simply hasn't used enough CPU time to measure. The amount of time the process spends in sleep() doesn't count against the program's CPU time, as times() measures The CPU time charged for the execution of user instructions (among other related times) which is the amount of time the process has spent executing user/kernel code.
Change your program to the following which uses more CPU and can therefore be measured:
#include <sys/times.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
long clock_times;
struct tms begintime;
unsigned i;
for (i = 0; i < 1000000; i++)
time(NULL); // An arbitrary library call
if((clock_times=times(&begintime))==-1)
perror("get times error");
else
{
printf("%ld %ld %ld %ld\n",
(long)begintime.tms_utime,
(long)begintime.tms_stime,
(long)begintime.tms_cutime,
(long)begintime.tms_cstime);
}
return 0;
}
Your code using close to none CPU time, so results are correct. Sleep suspends your program execution - everything that happens in this time is not your execution time, so it wouldn't be counted.
Add empty loop and you'll see the difference. (ofc., disable compiler optimisations - or empty loop will be removed).
Take a look at 'time' program output (time ./a.out) - it prints 'real' time (estimated by gettimeofday(), i suppose), user time (time wasted by your userspace code) and system time (time wasted within system calls - e.g. write to file, open network connection, etc.).
(sure, by 'wasted' i mean 'used', but whatever)