#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.
Related
The program should print to the screen every 5 seconds and state "alive at %d milliseconds\n". When the user types in <Control><A> for the polling program or <Control><C> for the interrupt version, the program should stop and output:
program terminated by user. Total time is %d milliseconds %d seconds\n.
My Program:
#include <signal.h>
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
volatile sig_atomic_t print_flag = false;
void handle_alarm( int sig ) {
print_flag = true;
}
int main() {
struct timeval start, stop;
double secs = 0;
char key_press;
char input_key;
int ascii_value;
float time_taken;
clock_t t;
t = clock();
gettimeofday(&start, NULL);
signal( SIGALRM, handle_alarm );
alarm( 5 );
for (;;) {
if ( print_flag ) {
print_flag = false;
alarm( 5 );
gettimeofday(&stop, NULL);
secs = (double)(stop.tv_usec - start.tv_usec) / 1000000 + (double)(stop.tv_sec - start.tv_sec) * 1000;
printf("Alive at %f ms \n",secs);
input_key=getchar();
ascii_value=input_key;
if(ascii_value==1) {
t = clock() - t;
time_taken = ((float)t)/CLOCKS_PER_SEC; // in seconds
printf("total time taken= %f sec", time_taken);
break;
}
}
}
}
I want the program to run continuously but when I press ctrl a it should terminate. The program prints "Alive at 5000.000 ms and stops printing. The program prints infinitely every 5 seconds if I don't add the code for terminating using ctrl A. How to make it work?
When you ask for input in this way, you are using synchronous blocking I/O. The process hangs until input is given. If you wish for your program to continue functioning while waiting for input you need to delve into asynchronous non-blocking I/O. Look up the select() function
https://en.wikipedia.org/wiki/Asynchronous_I/O
https://www.gnu.org/software/libc/manual/html_node/Waiting-for-I_002fO.html
After you do print_flag = false; in the for loop, you never set print_flag back to true again. Hence, the code in the if ( print_flag ) block is executed only once.
How to make it work?
To make it work, you need to set print_flag to true before you check whether it is true.
I have a question I am writing a code that find the perfect number by brute forcing the algorithm which is required by my assignment. I want to see how far the ranges goes in 15 seconds. I tried using a while loop and an alarm but it seems to not work at all. How would I go from there?
Thanks
Heres my code:
#define _POSIX_SOURCE
#define _BSD_SOURCE
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
volatile int stop=0;
void sigalrm_handler( int sig ){
stop = 1;
}
int main(int argc, char **argv){
struct sigaction sact;
int num_sent = 0;
sigemptyset(&sact.sa_mask);
sact.sa_flags = 0;
sact.sa_handler = sigalrm_handler;
sigaction(SIGALRM, &sact, NULL);
alarm(15); /* Request SIGALRM in 60 seconds */
while (!stop) {
for (;;){
for (;;){
}
}
}
printf("%d \n", num_sent);
exit(0);
}
Even if the alarm gets triggered and set stop to a non-zero value you won't notice since your for loop doesn't return to the outer while. You need to apply the condition to all loops that should be stopped:
while (!stop) {
for (;!stop;){
for (;!stop;){
}
}
}
An alternative to alarm is simply checking whether you crossed a certain timepoint:
time_t end = time(0) + 15;
while (end < time(0)) {
for (;end < time(0);){
for (;end < time(0);){
}
}
}
I want to create a timer in our C program so that it can print the variable after every 1 second.
Can anybody help me in doing this?
Don't use busy waiting, because you've got 100% CPU utilization.
You must use system function which turns process into sleeping mode for example select():
#include <stdio.h>
#include <sys/select.h>
void your_callback()
{
printf("%s\n", __FUNCTION__);
}
int main()
{
struct timeval t;
while (1) {
t.tv_sec = 1;
t.tv_usec = 0;
select(0, NULL, NULL, NULL, &t);
your_callback();
}
return 0;
}
If all you are interested in doing is printing the value of a variable at a one second interval, using time(2) or clock(3) as suggested in the other answers might suffice. In general, I would not recommend these busy-waiting techniques.
If your program is more complex, I suggest you investigate using the alarm(2) or settimer(2) function to asynchronously deliver a signal to your application at a one second interval.
The following example uses select(2) to block indefinitely in order to minimize CPU usage associated with busy-waiting techniques. The blocking select() call is interrupted and returns when a signal is caught. In the case of the SIGALRM signal, the print_variable flag is set and the value of variable is printed.
Example 1: using alarm()
#include <signal.h>
#include <stdio.h>
#include <sys/select.h>
#include <unistd.h>
volatile unsigned int variable = 0;
volatile unsigned int print_variable = 0;
void alarm_handler(int signum)
{
variable++;
print_variable = 1;
alarm(1);
}
int main()
{
signal(SIGALRM, alarm_handler);
alarm(1);
for (;;)
{
select(0, NULL, NULL, NULL, NULL);
if (print_variable)
{
printf("Variable = %u\n", variable);
}
}
}
Note: Error checking was omitted from the above code for simplicity.
A printf() function could have been called inside the SIGALRM handler, but calling non-reentrant functions in a signal handler is generally discouraged.
A timeout of one second can also be passed to select(), but if it were interrupted by any signal, additional logic is necessary to ensure that the remainder of the one second timeout is honored. Fortunately on Linux, select() modifies the timeout value to reflect the amount of time not slept. This allows interruption cases to be detected followed by subsequent call(s) select() to complete the timeout.
Example 2: using select()
#include <errno.h>
#include <stdio.h>
#include <sys/select.h>
volatile unsigned int variable = 0;
int main()
{
struct timeval tv;
int val;
for (;;)
{
tv.tv_sec = 1;
tv.tv_usec = 0;
do
{
val = select(0, NULL, NULL, NULL, &tv);
} while (val != 0 && errno == EINTR);
printf("Variable = %u\n", ++variable);
}
}
If you want only second precision. Use time(0) which returns current time if time.h is included.
update:
Adding simple example which prints 10 in every second during 20 seconds:
#include <time.h>
#include <stdio.h>
int main()
{
int a = 10;
int num = 20;
int c = time(0);
while(n--)
{
printf("%d\n", a);
while(!(time(0) - c));
c = time(0);
}
return 0;
}
use time(0) see this example
/* timer.c */
#include <stdio.h>
#include <time.h>
void delay_sec( int seconds ){
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC;
while (clock() < endwait) {}
}
int main (void){
time_t rawtime, ini_time, now;
struct tm *ptm;
time ( &ini_time );
for(;;){
time ( &rawtime );
//ptm = gmtime ( &rawtime );
//printf ("%2d:%02d:%02d\n", ptm_2->tm_hour, ptm_2->tm_min, ptm_2->tm_sec);
now = rawtime - ini_time;
ptm = gmtime ( &now );
printf ("%2d:%02d:%02d\n", ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
delay_sec(1);
}
return 0;
}
I believe you know 1000 Milliseconds equals to 1 Second.
#include <stdio.h>
#include <time.h>
#define mydelay 1000
void delay(int mseconds)
{
clock_t wait = mseconds + clock();
while (wait > clock());
}
int main()
{
int i=100;
while(1)
{
printf("%d\n",i);
delay(mydelay);
}
return 0;
}
A simple example which prints the value of the variable a for every 1 sec:
#include<stdio.h>
void main(void)
{
int a = 10;
while(a--)
{
printf("Value of a = %d\n", a);
sleep(1);
}
}
Output:
Value of a = 9
...
value of a = 0
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().
I want to run an infinite loop for a while. Basically, i want to have something like this
//do something
while(1){
//do some work
}
//do some other thing
but i want the running time of the loop to be fixed, example, the loop could be running for 5 seconds.
Do somebody have an idea?
Just do sleep(5) (include unistd.h). You can use it like this:
// do some work here
someFunction();
// have a rest
sleep(5);
// do some more work
anotherFunction();
If you're doing work inside the loop, you can do (include time.h):
// set the end time to the current time plus 5 seconds
time_t endTime = time(NULL) + 5;
while (time(NULL) < endTime)
{
// do work here.
}
Try using clock().
#include <time.h>
clock_t start = clock();
while (1)
{
clock_t now = clock();
if ((now - start)/CLOCKS_PER_SEC > 5)
break;
// Do something
}
First of all, consider using the sleep function if possible. If you have to do actual work for a specified time period, which I find unlikely, the following ugly solution would work:
#include <signal.h>
int alarmed = 0;
void sigh(int signum) {
alarmed = 1;
}
int main(void){
/* ... */
signal(SIGALRM, &sigh);
alarm(5); // Alarm in 5 seconds
while(!alarmed) {
/* Do work */
}
/* ... */
}
A solution using time.h would also be possible, and perhaps simpler and/or more accurate, depending on context:
#include <time.h>
int main(void){
/* ... */
clock_t start = clock();
while(clock() - start < 5 * CLOCKS_PER_SEC) {
/* Do work */
}
/* ... */
}
Pseudo-code:
starttime = ...;
while(currentTime - startTime < 5){
}
If you don't want to call a time getting function each time through the loop and are on a system that has alarm (POSIXes like Unix, Linux, BSD...) you can do:
static volatile int timeout = 0;
void handle_alrm(int sig) {
timeout = 1;
}
int main(void) {
signal(SIGALRM, handle_alrm);
...
timeout = 0;
alarm(5);
while (!timeout) {
do_work();
}
alarm(0); // If the signal didn't fire yet we can turn it off now.
...
Signals can have other side effects (like kicking you out of system calls). You should look into these before relying on them.
Not tested; resolution is very coarse.
#include <time.h>
#define RUNTIME 5.0 /* seconds */
double runtime = 0;
double start = clock(); /* automatically convert clock_t to double */
while (runtime < RUNTIME / CLOCKS_PER_SEC) {
/* work */
runtime = clock() - start;
}
If /* work */ takes more than 5 seconds, the loop will take more than 5 seconds.
If /* work */ takes 1.2 seconds, the loop will execute approximately 5 times for a total of 6 seconds