Calculate the execution time of program in C - 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;
}

Related

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

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

How to record elaspsed wall time in 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);
}

linux start time and stop timer is not working ?

#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
typedef unsigned int uint32;
#define million 1000000L
long duration2ms, duration10ms, duration100ms;
double Task2ms_Raster, Task10ms_Raster, Task100ms_Raster;
timer_t firstTimerID, secondTimerID, thirdTimerID;
void TASK1(Task2ms_Raster) {
struct timespec start, stop;
int a, b, c;
uint32 StartTime, StopTime;
a=100, b=2;
if((StartTime = clock_gettime(CLOCK_REALTIME, &start)) == -1) {
perror("clock gettime");
}
printf("start time is= %ld\n", StartTime);
//I am performing some computation like
a = a + 100;
b = a + 120;
a = a + b;
b = a;
c = b;
if((StopTime = clock_gettime( CLOCK_REALTIME, &stop)) == -1) {
perror("clock gettime");
}
printf("stop time is= %ld\n", StopTime);
duration2ms = (stop.tv_sec - start.tv_sec) +
(double)(stop.tv_nsec - start.tv_nsec) /
(double)million;
printf("time difference is= %ld\n", duration2ms);
}
I created the timer and calling the task for every 2ms, 10ms and 100ms. The above is the code for 2ms task. I want to calculate the start time and stop time for performing some computation within the task and finally want to know the time difference between that. when I run my application, it is just displaying the time difference (i.e duration2ms). It is not printing the StartTime and StopTime. Could someone please help me.
If you read the manual page of clock_gettime you would see that
clock_gettime() return 0 for success, or -1 for failure.
So, you are printing the return code only. To print start time and stop time you will need to print the content of variables start and stop. For example:
printf("Start time: %d.%09d\n", start.tv_sec, start.tv_nsec);
what u need is
uint64_t u64StartTime = (start.tv_sec * 100000000) + start.tv_nsec;

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