C Elapsed time linux - c

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.

Related

How to get execution time of c program?

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

Measuring execution time with clock in sec in C not working

I'm trying to measure execution time in C using clock() under linux using the following:
#include <time.h>
#include <stdio.h>
#include <unistd.h>
int main(int argc, char const* argv[])
{
clock_t begin, end;
begin = clock();
sleep(2);
end = clock();
double spent = ((double)(end-begin)) / CLOCKS_PER_SEC;
printf("%ld %ld, spent: %f\n", begin, end, spent);
return 0;
}
The output is:
1254 1296, spent: 0.000042
The documentation says to divide the clock time by CLOCKS_PER_SEC to get the execution time in sec, but this seems pretty incorrect for a 2sec sleep.
What's the problem?
Sleeping takes almost no execution time. The program just has to schedule its wakeup and then put itself to sleep. While it's asleep, it is not executing. When it's woken up, it doesn't have to do anything at all. That all takes a very tiny fraction of a second.
It doesn't take more execution time to sleep longer. So the fact that there's a 2 second period when the program is not executing has no effect.
clock measures CPU time (in Linux at least). A sleeping process consumes no CPU time.
If you want to measure a time interval as if with a stopwatch, regardless of what your process is doing, use clock_gettime with CLOCK_MONOTONIC.
man clock() has the answer:
The clock() function returns an approximation of processor time used by the program.
Which clearly tells that clock() returns the processor time used by the program, not what you were expecting the total run time of the program which is typically done using gettimeofday.

Measuring time with time.h?

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

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 (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);

Checking Process duration with C

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?

Resources