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
Related
I read an article form geeksforgeeks.The code shows a funciton to measure the time function cost.
In my machine ,I always got 0.000000 no matter how long I press enter.
I print t = clock() - t; t always equal to 0.00000,I rewrite the statement to this,still got 0.000000.
clock_t m;
m = clock() - t;
gcc version in centos7
[root#localhost log]# gcc --version
gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-28)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
/* Program to demonstrate time taken by function fun() */
#include <stdio.h>
#include <time.h>
// A function that terminates when enter key is pressed
void fun()
{
printf("fun() starts \n");
printf("Press enter to stop fun \n");
while(1)
{
if (getchar())
break;
}
printf("fun() ends \n");
}
// The main program calls fun() and measures time taken by fun()
int main()
{
// Calculate the time taken by fun()
clock_t t;
t = clock();
fun();
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds
printf("fun() took %f seconds to execute \n", time_taken);
return 0;
}
Hello try this instead:
unsigned int t=time(0);
fun();
unsigned int result=time(0)-t; // result is the time taken by fun
In case you're trying to measure "CPU time used" (and not "wall clock time spent waiting for user to press a key"), then...
Imagine if the OS has a timer that generates an IRQ 10 times per second, and the IRQ handler just does ticks++; and clock() is just return ticks;. In this case, CLOCKS_PER_SEC would be 10.
Now, if you call clock() once just before the timer IRQ occurs and again immediately after the timer IRQ occurs, the difference between the values returned might be 1 (equal to 100 ms) even significantly less time passed between calls to clock().
Alternatively; if you call clock() once immediately after the timer IRQ occurs and again just before the timer IRQ occurs again, the difference between the values returned might be 0, even significantly more time passed between calls to clock().
Essentially, the difference between values returned by clock() is "up to 1/CLOCKS_PER_SEC sooner than you think" and "up to 1/CLOCKS_PER_SEC longer than you think".
Note that the value of CLOCKS_PER_SEC is implementation defined. Depending on various things (which version of which OS running on which hardware, with which C library) CLOCKS_PER_SEC can be anything, and could be as low as 10 and could be as high has 4 billion.
clock() measures the CPU time, that is the time that the processor has been active. You may want to measure wall clock time instead, which is the number of seconds from the start to the end of the function run:
struct timeval start;
gettimeofday(&start, 0);
fun();
struct timeval end;
gettimeofday(&end, 0);
double time_taken = (end.tv_sec - start.tv_sec)
+ (end.tv_usec - start.tv_usec)*1e-6;
To make this work, you must also include <sys/time.h>
I code inside a virtual machine( Linux Ubuntu) that's installed on a windows.
According to this page, the CLOCKS_PER_SEC value in the library on Linux should always be 1 000 000.
When I run this code:
int main()
{
printf("%d\n", CLOCKS_PER_SEC);
while (1)
printf("%f, %f \n\n", (double)clock(), (double)clock()/CLOCKS_PER_SEC);
return 0;
}
The first value is 1 000 000 as it should be, however, the value that should show the number of seconds does NOT increase at the normal pace (it takes between 4 and 5 seconds to increase by 1)
Is this due to my working on a virtual machine? How can I solve this?
This is expected.
The clock() function does not return the wall time (the time that real clocks on the wall display). It returns the amount of CPU time used by your program. If your program is not consuming every possible scheduler slice, then it will increase slower than wall time, if your program consumes slices on multiple cores at the same time it can increase faster.
So if you call clock(), and then sleep(5), and then call clock() again, you'll find that clock() has barely increased at all. Even though sleep(5) waits for 5 real seconds, it doesn't consume any CPU, and CPU usage is what clock() measures.
If you want to measure wall clock time you will want clock_gettime() (or the older version gettimeofday()). You can use CLOCK_REALTIME if you want to know the civil time (e.g. "it's 3:36 PM") or CLOCK_MONOTONIC if you want to measure time intervals. In this case, you probably want CLOCK_MONOTONIC.
#include <stdio.h>
#include <time.h>
int main() {
struct timespec start, now;
clock_gettime(CLOCK_MONOTONIC, &start);
while (1) {
clock_gettime(CLOCK_MONOTONIC, &now);
printf("Elapsed: %f\n",
(now.tv_sec - start.tv_sec) +
1e-9 * (now.tv_nsec - start.tv_nsec));
}
}
The usual proscriptions against using busy-loops apply here.
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.
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);
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?