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);
}
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);
}
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
#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().