#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;
Related
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;
}
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);
}
#include <features.h>
#include <time.h>
#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=1, b=2, c=3;
if((StartTime = clock_gettime(CLOCK_REALTIME, &start)) == -1) {
perror("clock gettime");
}
a= b+c;
b = c+a;
c= a+b;
b = c+a;
c= a+b; a= b+c;
b = c+a;
c= a+b; a= b+c;
b = c+a;
c= a+b; a= b+c;
b = c+a;
c= a+b; a= b+c;
b = c+a;
c= a+b; a= b+c;
b = c+a;
c= a+b; a= b+c;
b = c+a;
c= a+b;
// I did several times like this.
printf("ETAS\n");
printf("ETAS1\n");
if((StopTime = clock_gettime( CLOCK_REALTIME, &stop)) == -1) {
perror("clock gettime");
}
duration2ms = (stop.tv_sec - start.tv_sec) +
(double)(stop.tv_nsec - start.tv_nsec) /
(double)million;
printf("time difference is= %ld\n", duration2ms);
}
void TASK2(Task10ms_Raster) {
struct timespec start, stop;
if(clock_gettime( CLOCK_REALTIME, &start) == -1) {
perror("clock gettime");
}
printf("ETAS2\n");
printf("ETAS3\n");
if(clock_gettime(CLOCK_REALTIME, &stop) == -1) {
perror("clock gettime");
}
duration10ms = (stop.tv_sec - start.tv_sec) +
(double)( stop.tv_nsec - start.tv_nsec) /
(double)million;
printf("time difference is= %ld\n", duration10ms);
}
void TASK3(Task100ms_Raster) {
struct timespec start, stop;
if(clock_gettime( CLOCK_REALTIME, &start) == -1) {
perror("clock gettime");
}
printf("ETAS4\n");
printf("ETAS5\n");
if((clock_gettime(CLOCK_REALTIME, &stop)) == -1) {
perror("clock gettime");
}
duration100ms = (stop.tv_sec - start.tv_sec) +
(double)(stop.tv_nsec - start.tv_nsec) /
(double)million;
printf( "time difference is= %ld\n", duration100ms );
}
static void timerHandler(int sig, siginfo_t *si, void *uc) {
timer_t *tidp;
tidp = si->si_value.sival_ptr;
if (*tidp == firstTimerID)
TASK1(Task2ms_Raster);
else if(*tidp == secondTimerID)
TASK2(Task10ms_Raster);
else if(*tidp == thirdTimerID)
TASK3(Task100ms_Raster);
}
static int makeTimer(char *name,
timer_t *timerID,
int expireMS,
int intervalMS) {
struct sigevent te;
struct itimerspec its;
struct sigaction sa;
int sigNo = SIGRTMIN;
/* Set up signal handler. */
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = timerHandler;
sigemptyset(&sa.sa_mask);
if(sigaction(sigNo, &sa, NULL) == -1) {
perror("sigaction");
}
/* Set and enable alarm */
te.sigev_notify = SIGEV_SIGNAL;
te.sigev_signo = sigNo;
te.sigev_value.sival_ptr = timerID;
timer_create(CLOCK_REALTIME, &te, timerID);
its.it_interval.tv_sec = 0;
its.it_interval.tv_nsec = intervalMS * 1000000;
its.it_value.tv_sec = 0;
its.it_value.tv_nsec = expireMS * 1000000;
timer_settime(*timerID, 0, &its, NULL);
return 1;
}
int main(void) {
makeTimer("First Timer", &firstTimerID, 2, 2); //2ms
makeTimer("Second Timer", &secondTimerID, 10, 10); //10ms
makeTimer("Third Timer", &thirdTimerID, 100, 100); //100ms
while(1) {
sleep(100);
}
}
I created a timer to call the task for every 2ms, 10ms and 100ms. The tasks are just printing the value and calculating the start time and stop time for printing the value. when i run the above program, it is not displaying time difference between the start time and stop time (i.e duration2ms, duration 10ms nd duration100ms). could someone please help me.
The problem is that you don't save your timing values in TASK*() anywhere. This means clock_gettime() gets called twice in a row, having little or no time spent in between. What you should do is something along the lines of following:
#include <features.h>
#include <time.h>
#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;
timer_t tmr;
struct timespec prev;
static void handle_timer(int sig, siginfo_t *si, void *uc) {
timer_t *tidp;
struct timespec current;
tidp = si->si_value.sival_ptr;
clock_gettime(CLOCK_REALTIME, ¤t);
printf("dif between calls to handle_timer: %ld\n",
current.tv_sec - prev.tv_sec);
prev = current;
}
int main(int argc, char **argv) {
struct sigevent se;
struct itimerspec its;
struct sigaction sa;
clock_gettime(CLOCK_REALTIME, &prev);
/* Set up signal handler. */
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = handle_timer;
sigemptyset(&sa.sa_mask);
if (sigaction(SIGRTMIN, &sa, NULL) == -1)
perror("sigaction");
/* Set and enable alarm */
se.sigev_notify = SIGEV_SIGNAL;
se.sigev_signo = SIGRTMIN;
se.sigev_value.sival_ptr = &tmr;
timer_create(CLOCK_REALTIME, &se, &tmr);
its.it_interval.tv_sec = 1;
its.it_value.tv_sec = 1;
its.it_value.tv_nsec = 0;
timer_settime(&tmr, 0, &its, NULL);
while(1)
sleep(100);
return 0;
}
The difference here is that we're actually saving the time when handle_time() was called and then calculating the difference against the saved time.
The time difference is going to show zero in all cases because you are measuring the time it takes to print two lines, which is very fast. You are not timing the time between invocations of each task.
If you want to measure the time between invocations of the task, you need to preserve the time. As an example, I'll show one task:
void TASK3(Task100ms_Raster) {
static struct timespec start, stop = { .tv_sec = -1 }; // static duration!
if (stop.tv_sec < 0) {
(void) clock_gettime( CLOCK_REALTIME, &stop); // first time run
}
start = stop; // start from previous stop time
// do whatever here
(void) clock_gettime( CLOCK_REALTIME, &stop);
duration100ms = (stop.tv_sec - start.tv_sec)
+ (double)(stop.tv_nsec - start.tv_nsec)
/ (double)million;
printf( "time difference is= %ld\n", duration100ms );
}
#include <stdio.h>
#include <time.h>
#include <windows.h>
void Task()
{
printf("Hi");
}
int main ( ) {
time_t t;
clock_t start, end;
long i;
long count;
double x = 0.0;
count = 2;
start = clock();
time(&t);
printf(ctime(&t));
printf( "Counting to %ld\n", count );
if(count)
{
Task();
}
end = clock();
printf( "That took %f seconds and I counted up to %ld", (((double)(end-start)/CLOCKS_PER_SEC)), count );
printf( "\nThat also took %d clock tics\n ", clock());
return 0;
}
I want to get the start time and end time taken to execute the Task function. I am trying to create interrupt for the Task function but displaying Hi in the program. I am not successful with that. So could you please anyone can guide me regarding this.
Try starting with the Multimedia Timers. Another possible approach might be using CreateTimerQueueTimer() and friends.
There is no way of having interrupts in user-mode, only kernel-mode drivers can service interrupt requests.
However you can have a callback function called by the OS in a periodic way. On Windows you can achieve this using the multimedia times (however declared obsolete by Microsoft) or timer queue timers (check this, for example: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682485%28v=vs.85%29.aspx).
Here is an old test program I wrote that uses the Multimedia timers (obsolete but they still work on recent Windows versions...):
#include <stdio.h>
#include <windows.h>
volatile long timer = 0;
// Will be called every 1 ms
void CALLBACK timer_func(UINT uTimerID, UINT uMsg, DWORD *dwUser,
DWORD *dw1, DWORD *dw2)
{
timer++;
}
int main(int argc, char *argv[])
{
MMRESULT id = timeSetEvent(1, 0, (LPTIMECALLBACK) timer_func, NULL, TIME_PERIODIC);
printf("Waiting 10 seconds... ");
fflush(stdout);
Sleep(10000);
printf("ok. Timer = %ld.\n", timer);
timeKillEvent(id);
return 0;
}
If you just want to precisely measure how long a function call lasts, just use QueryPerformanceCounter() and QueryPerformanceFrequency():
#include <windows.h>
#include <stdio.h>
void task()
{
// do something...
}
int main()
{
LARGE_INTEGER start, stop, freq;
QueryPerformanceCounter(&start);
task();
QueryPerformanceCounter(&stop);
QueryPerformanceFrequency(&freq);
double time_len = (stop.QuadPart - start.QuadPart) / (double) freq.QuadPart;
printf("Task length: %0.8f seconds.\n", time_len);
}
New answer after discussion (see comments of my previous answer): you can implement an equivalent to the GetStopWatch() function you want this way:
#include <windows.h>
#include <stdio.h>
#include <stdint.h>
// assuming we return times with microsecond resolution
#define STOPWATCH_TICKS_PER_US 1
uint64_t GetStopWatch()
{
LARGE_INTEGER t, freq;
uint64_t val;
QueryPerformanceCounter(&t);
QueryPerformanceFrequency(&freq);
return (uint64_t) (t.QuadPart / (double) freq.QuadPart * 1000000);
}
void task()
{
// do something...
}
int main()
{
uint64_t start = GetStopWatch();
task();
uint64_t stop = GetStopWatch();
printf("Elapsed time (microseconds): %lld\n", stop - start);
}
Hope this helps.
I have tried the function:
#include <stdio.h>
#include <time.h>
int main ()
{
time_t seconds;
seconds = time (NULL);
printf ("%ld hours since January 1, 1970", seconds/3600);
return 0;
}
It is useful but it returns the time in number of seconds since 1970. In my case, I would like to obtain a result with more precision, to distinguish two events happening in the same second. Is it possible to do that?
Use gettimeofday(3). It allows you to get the time in microseconds.
#include <stdio.h>
#include <sys/time.h>
int main(int argc, char **argv)
{
struct timeval tv = { 0 };
gettimeofday(&tv, NULL);
printf("sec: %ld usec: %ld\n", tv.tv_sec, tv.tv_usec);
return 0;
}
or with clock_gettime():
#include <stdio.h>
#include <time.h>
int main(int argc, char **argv)
{
struct timespec ts = { 0 };
clock_gettime(CLOCK_REALTIME, &ts);
printf("sec: %ld nsec: %ld\n", ts.tv_sec, ts.tv_nsec);
return 0;
}
Try clock_gettime . It gives additional info in nanoseconds.
Basic Standard C does not describe any calendar time functions with a resolution better than 1 second.
You have to use extensions.
For POSIX, try gettimeofday() (obsolescent) clock_gettime().
For Windows, apparently, you can use GetSystemTime().