How to record elaspsed wall time in C? - c

I'm trying to record the time my program takes to finish in seconds, with sub-second accuracy.
I'm not recording CPU time or cycles, I simply want to be able to mark a start point (Wall Clock time), then at the end of my program mark a finish (Wall Clock time), and calculate the delta.

Have a look at the function:
int clock_gettime(clockid_t clk_id, struct timespec *tp);
The function will fill the structure struct timespec you provide. Here is its definition:
struct timespec {
time_t tv_sec; /* secondes */
long tv_nsec; /* nanosecondes */
};
So the returned time in nanosecondes is: tp->tv_sec * 1e9 + tp->tv_nsec.
You can find all the possible clk_id in the man. I would recommend you to use CLOCK_MONOTONIC as it guarantees you that the time given will always be continuous, even if the time of the system is modified.

Just call time(NULL) to get the current time and use difftime to calculate the time between two points.
#include <time.h>
// ...
time_t start = time(NULL);
// do stuff here
time_t end = time(NULL);
printf("Took %f seconds\n", difftime(end, start));

This displays start/end time stamps and calculates a delta in seconds.
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
void print_timestamp(char *, time_t);
int main (int argc, char *argv[]) {
time_t start = time(0);
print_timestamp("Start: ", start);
sleep(2);
time_t end = time(0);
print_timestamp("End: ", end);
double diff = difftime(end, start);
printf("Elapsed: %5.2lf seconds\n", diff);
}
void
print_timestamp(char *msg, time_t time) {
struct tm *tm;
if ((tm = localtime (&time)) == NULL) {
printf ("Error extracting time stuff\n");
return;
}
printf ("%s %04d-%02d-%02d %02d:%02d:%02d\n",
msg,
1900 + tm->tm_year,
tm->tm_mon+1,
tm->tm_mday,
tm->tm_hour,
tm->tm_min,
tm->tm_sec);
}
Sample output:
Start: 2017-02-04 15:33:36
End: 2017-02-04 15:33:38
Elapsed: 2.00 seconds

You may also be able to use the time command available on (at least) Unix systems.
After compiling your program, run the command like this:
# compile your code
$ gcc foo.c -o foo
# compute the time
$ time ./foo

You can use the clock() function to record the number of ticks taken and then convert this to seconds:
#include <time.h>
#include <stdio.h>
#include <math.h>
int main () {
clock_t start_t = clock();
double a=0;
for(int i=0; i< 10000000; i++) {
a+=sqrt(a);
}
clock_t end_t = clock();
double total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
printf("Total time taken by CPU: %lf\n", total_t );
return(0);
}

Related

Calculate the execution time of program in C

I want to calculate and print the time taken by my C program to execute using ftime() specifically..
I am seeing the man page for ftime() but I don't understand how to use it!
As #KamilCuk correctly mentioned, ftime() is deprecated and should be displaced with clock_gettime(), see the man page.
This and more examples explained here
#include <stdio.h>
#include <time.h> // for clock_t, clock()
#include <unistd.h> // for sleep()
#define BILLION 1000000000.0
// main function to find the execution time of a C program
int main()
{
struct timespec start, end;
clock_gettime(CLOCK_REALTIME, &start);
// do some stuff here
sleep(3);
clock_gettime(CLOCK_REALTIME, &end);
// time_spent = end - start
double time_spent = (end.tv_sec - start.tv_sec) +
(end.tv_nsec - start.tv_nsec) / BILLION;
printf("Time elpased is %f seconds", time_spent);
return 0;
}
If you're in Linux, just use 'time' command to measure the program execution time:
time ./my_programm
Here some code with clock_gettime()
#include <stdio.h> //For printf
#include <time.h> //For clock_gettime
int main (void)
{
//Structs for saving timestamps
struct timespec mt1, mt2;
//Variable for time delta calculating
long int tt;
//Get current time
clock_gettime (CLOCK_REALTIME, &mt1);
/* do some stuff here */
//Get current time again
clock_gettime (CLOCK_REALTIME, &mt2);
//Calculate the delta between two timestamps
tt=1000000000*(mt2.tv_sec - mt1.tv_sec)+(mt2.tv_nsec - mt1.tv_nsec);
//Print the delta
printf ("Time spent: %ld nsec / %ld ms\n", tt, tt/1000000);
return 0;
}

Function clock() in C

While studying the clock () function located in time.h, I asked myself the question of making a simple program to see how it worked. I was surprised when running this program the result shown is 0, while what I expected was 2. Where am I wrong?
int main(int argc, char const *argv[]){
int msec = 0;
clock_t before = clock();
sleep(2);
clock_t difference = clock() - before;
msec = difference * 1000 / CLOCKS_PER_SEC;
printf("Time taken %d seconds\n",msec/1000);
}
clock measures processor time used by your program. Your program does not use processor time while it is sleeping. The rest of your program uses less than a millisecond of time.
To measure “wall clock” or “real world” time, use time, and use difftime to subtract to time_t values, the type returned by time:
#include <stdio.h>
#include <time.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
time_t before = time(NULL);
sleep(2);
double difference = difftime(time(NULL), before);
printf("The time taken was %g seconds.\n", difference);
}

Set time_t to milliseconds

I have a function and I want the function to stop running once it has been running for a certain number of milliseconds. This function works for seconds but I want to test it for milliseconds. How do I do this? If I set eliminate = 1, it corresponds to 1 second. How do I set eliminate = 5 ms?
Function:
void clsfy_proc(S_SNR_TARGET_SET pSonarTargetSet, unsigned char *target_num, time_t eliminate)
{
// get timing
time_t _start = time(NULL);
time_t _end = _start + eliminate;
int _eliminate = 0;
//some code
time_t start = time(NULL);
time_t end = start + eliminate;
for(_tidx = 0; _tidx < pSonarTargetSet[_i].num; _tidx++) {
// check timing
time_t _current = time(NULL);
if (_current > _end) {
printf("clsfy_proc(1), Eliminate due to timeout\n");
_eliminate = 1;
break;
}
//some code
if (_eliminate == 1)
break;
}
//some code
}
time_t is an absolute time, represented as the integer number of seconds since the UNIX epoch (midnight GMT, 1 January 1970). It is useful as an unambiguous, easy-to-work-with representation of a point in time.
clock_t is a relative measurement of time, represented by an integer number of clock ticks since some point in time (possibly the computer's bootup, but no guarantees, as it may roll over quite often). There are CLOCKS_PER_SEC clock ticks per second; the value of this constant can vary between different operating systems. It is sometimes used for timing purposes, but it is not very good at it due to its relatively low resolution.
One small example for clock_t:
#include <time.h>
#include <stdio.h>
int main () {
clock_t start_t, end_t, total_t;
int i;
start_t = clock();
printf("Starting of the program, start_t = %ld\n", start_t);
for(i=0; i< 10000000; i++) { }
end_t = clock();
printf("End of the big loop, end_t = %ld\n", end_t);
total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
printf("Total time taken by CPU: %f\n", total_t );
return(0);
}
You can use getrusage().
Please see the example:
Source: http://www.cs.tufts.edu/comp/111/examples/Time/getrusage.c
#include <stdio.h>
#include <sys/time.h>
#include <sys/resource.h>
///////////////////////////////////
// measure user and system time using the "getrusage" call.
///////////////////////////////////
//struct rusage {
// struct timeval ru_utime; /* user CPU time used */
// struct timeval ru_stime; /* system CPU time used */
// long ru_maxrss; /* maximum resident set size */
// long ru_ixrss; /* integral shared memory size */
// long ru_idrss; /* integral unshared data size */
// long ru_isrss; /* integral unshared stack size */
// long ru_minflt; /* page reclaims (soft page faults) */
// long ru_majflt; /* page faults (hard page faults) */
// long ru_nswap; /* swaps */
// long ru_inblock; /* block input operations */
// long ru_oublock; /* block output operations */
// long ru_msgsnd; /* IPC messages sent */
// long ru_msgrcv; /* IPC messages received */
// long ru_nsignals; /* signals received */
// long ru_nvcsw; /* voluntary context switches */
// long ru_nivcsw; /* involuntary context switches */
//};
//struct timeval
// {
// long int tv_sec; /* Seconds. */
// long int tv_usec; /* Microseconds. */
// };
main () {
struct rusage buf;
// chew up some CPU time
int i,j; for (i=0,j=0; i<100000000; i++) { j+=i*i; }
getrusage(RUSAGE_SELF, &buf);
printf("user seconds without microseconds: %ld\n", buf.ru_utime.tv_sec);
printf("user microseconds: %ld\n", buf.ru_utime.tv_usec);
printf("total user seconds: %e\n",
(double) buf.ru_utime.tv_sec
+ (double) buf.ru_utime.tv_usec / (double) 1000000);
}

time on ecos (or qemu )

I'm working with real time operating system Ecos.
i run this code on ubuntu :
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
static int tv_diff(struct timeval *t1, struct timeval *t2)
{
return
(t1->tv_sec - t2->tv_sec) * 1000 +
(t1->tv_usec - t2->tv_usec) / 1000;
}
int main(void)
{
struct timespec ts;
struct timeval tv1, tv2;
printf("Hello, eCos !\n");
clock_gettime(1, &ts);
tv1.tv_sec = ts.tv_sec;
tv1.tv_usec = ts.tv_nsec / 1000;
printf("Time: %ld \n", tv1.tv_sec);
sleep(10);
clock_gettime(1, &ts);
tv2.tv_sec = ts.tv_sec;
tv2.tv_usec = ts.tv_nsec / 1000;
printf("Time: %ld \n", tv2.tv_sec);
printf("diff Time: %d \n", tv_diff(&tv2, &tv1));
return 0;
}
and it worked properly :
root#ubuntu:/home/feres/Bureau# ./amin
Hello, eCos !
Time: 45417
Time: 45427
diff Time: 10000
but when i run it on ecos ( wich it work on qemu ) it give me this results
Hello, eCos !
Time: 0
Time: 0
diff Time: 0
is there any missing package on ecos (or qemu) or is there any specific commande to get time on ecos (or qemu)
Looks like your ECOS-HAL is not correctly set up (so that the system tick gets updated on a regular basis).

sysconf(_SC_CLK_TCK) what does it return?

I was trying to understand various sysconf macros.I have written a program as below.
int main()
{
fprintf(stdout, "No. of clock ticks per sec : %ld\n",sysconf(_SC_CLK_TCK));
return 0;
}
I always get the result as 100.I am running it on a CPU that is clocked at 2.93GHz.What does the number 100 exactly mean.?
It's just the number of clock ticks per second, in your case the kernel is configured for 100 clocks per second (or 100Hz clock).
The number of clock ticks per second can be found by the sysconf system call,
printf ("_SC_CLK_TCK = %ld\n", sysconf (_SC_CLK_TCK));
A typical value of clock ticks per second is 100. That is, in this case, there is a clock tick every 10 milliseconds or 0.01 second. To convert the clock_t values, returned by times, into seconds one has to divide by the number of clock ticks per second. An example program using the times and sysconf (_SC_CLK_TCK) system calls is,
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <sys/times.h>
int main ()
{
clock_t ct0, ct1;
struct tms tms0, tms1;
int i;
if ((ct0 = times (&tms0)) == -1)
perror ("times");
printf ("_SC_CLK_TCK = %ld\n", sysconf (_SC_CLK_TCK));
for (i = 0; i < 10000000; i++)
;
if ((ct1 = times (&tms1)) == -1)
perror ("times");
printf ("ct0 = %ld, times: %ld %ld %ld %ld\n", ct0, tms0.tms_utime,
tms0.tms_cutime, tms0.tms_stime, tms0.tms_cstime);
printf ("ct1 = %ld, times: %ld %ld %ld %ld\n", ct1, tms1.tms_utime,
tms1.tms_cutime, tms1.tms_stime, tms1.tms_cstime);
printf ("ct1 - ct0 = %ld\n", ct1 - ct0);
}
Source:
http://www.softprayog.in/tutorials/linux-process-execution-time

Resources