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
Related
I am trying to implement a timer that continuously counts certain amount of time while the software is running. I wrote a dirty code to try how sys/time.h works.
My understanding is that if I set my it_interval struct to a non-zero value, then the timer should start counting again once it's done counting for the value stored in it_value struct.
However, my code stalls. Could someone tell me what I am missing in my code please? Also, I am using Linux.
#include <sys/time.h>
#include <stdio.h>
#include <stdint.h>
int main(void) {
struct itimerval timer1;
timer1.it_interval.tv_sec = 5;
timer1.it_interval.tv_usec = 0;
timer1.it_value.tv_sec = 5;
timer1.it_value.tv_usec = 0 ;
setitimer(ITIMER_REAL, &timer1, NULL);
printf( "init interval counter: %ld.%ld\n", timer1.it_interval.tv_sec,
timer1.it_interval.tv_usec);
printf( "init value counter: %ld.%ld\n\n", timer1.it_value.tv_sec,
timer1.it_value.tv_usec );
while(1) {
for (int i = 0; i < 100000000000000; i++){
getitimer(ITIMER_REAL, &timer1);
printf( "end interval counter: %ld.%ld\n",
timer1.it_interval.tv_sec, timer1.it_interval.tv_usec);
printf( "end value counter: %ld.%ld\n\n",
timer1.it_value.tv_sec, timer1.it_value.tv_usec );
}
}
return 0;
}
My output (shortened of course) is:
end interval counter: 5.0
end value counter: 0.8821
end interval counter: 5.0Alarm clock
Process returned 142 (0x8E) execution time: 5.033 s
Thank you in advance for your help!
setitimer(ITIMER_REAL,...) causes SIGALRM to be sent to the calling process upon timer expiry. SIGALRM is a normally deadly signal, whose default disposition is to kill the process.
If you want to prevent your process from being killed by this signal, you need to handle it somehow.
Example (prints EXPIRED from the handler every 100ms) based on your code:
#include <sys/time.h>
#include <stdio.h>
#include <stdint.h>
#include <signal.h>
#include <unistd.h>
void handler(int Sig)
{
(void)Sig;
char msg[]="EXPIRED\n";
ssize_t nwr = write(1,msg,sizeof(msg)-1); (void)nwr;
}
int main(void) {
struct itimerval timer1;
struct sigaction sa;
sa.sa_handler = handler;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sigaction(SIGALRM,&sa,0);
timer1.it_interval.tv_sec = 0;
timer1.it_interval.tv_usec = 100000;
timer1.it_value.tv_sec = 0;
timer1.it_value.tv_usec = 100000 ;
setitimer(ITIMER_REAL, &timer1, NULL);
printf( "init interval counter: %ld.%ld\n", timer1.it_interval.tv_sec,
timer1.it_interval.tv_usec);
printf( "init value counter: %ld.%ld\n\n", timer1.it_value.tv_sec,
timer1.it_value.tv_usec );
while(1) pause();
return 0;
}
#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 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);){
}
}
}
We want to add a timer to our C program under Linux platform.
We are trying to send the packets and we want to find out how many packets get sent in 1 minute. We want the timer to run at the same time as the while loop for sending the packet is being executed. For example:
while(1)
{
send packets;
}
This loop will keep on sending the packets until ctrl-z is pressed. The timer should be used to stop the loop after 60 seconds.
You could do something like this:
#include <signal.h>
#include <unistd.h>
#include <stdio.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(60); /* Request SIGALRM in 60 seconds */
while (!stop) {
send_a_packet();
num_sent++;
}
printf("sent %d packets\n", num_sent);
exit(0);
}
If loop overhead turns out to be excessive, you could amortize the overhead by sending N packets per iteration and incrementing the count by N each iteration.
Just check the time on every iteration of the loop and when 1 minute has elapsed, count how many packets you have sent.
Edit changed to reflect what the question actually asks!
time_t startTime = time(); // return current time in seconds
int numPackets = 0;
while (time() - startTime < 60)
{
send packet
numPackets++;
}
printf("Sent %d packets\n", numPackets);
Can also check this http://www.gnu.org/software/libc/manual/html_node/Setting-an-Alarm.html to set timers which will send signals to your process and you can stop the while loop.
Look at the standard time() function.
Here is code snippet of itimer that can be used for different time intervals on C with linux platform:
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
void timer_handler (int signum)
{
static int count = 0;
printf ("timer expired %d times\n", ++count);
}
int main ()
{
struct sigaction sa;
struct itimerval timer;
/* Install timer_handler as the signal handler for SIGVTALRM. */
memset (&sa, 0, sizeof (sa));
sa.sa_handler = &timer_handler;
sigaction (SIGVTALRM, &sa, NULL);
/* Configure the timer to expire after 1 sec... */
timer.it_value.tv_sec = 1;
timer.it_value.tv_usec = 0;
/* ... and every 1000 msec after that. */
timer.it_interval.tv_sec = 1;
timer.it_interval.tv_usec = 0;
/* Start a virtual timer. It counts down whenever this process is
* executing. */
setitimer (ITIMER_VIRTUAL, &timer, NULL);
/* Do busy work. */
while (1);
sleep(1);
}
hope it will help.
Use wheetimer (and its variant) data structures to implement timers.
man 3 sleep:
NAME
sleep - Sleep for the specified number of seconds
SYNOPSIS
#include < unistd.h >
unsigned int sleep(unsigned int seconds);
I need to call a function every second exactly as I want to store the data based on the every second so I cannot miss the second? What is best method in C?
Below is a skeleton of the timer_create method is this reliable enough?
#include <stdio.h>
#include <time.h>
#include <signal.h>
timer_t gTimerid;
void start_timer(void)
{
struct itimerspec value;
value.it_value.tv_sec = 1;
value.it_value.tv_nsec = 0;
value.it_interval.tv_sec = 1;
value.it_interval.tv_nsec = 0;
timer_create (CLOCK_REALTIME, NULL, &gTimerid);
timer_settime (gTimerid, 0, &value, NULL);
}
void stop_timer(void)
{
struct itimerspec value;
value.it_value.tv_sec = 0;
value.it_value.tv_nsec = 0;
value.it_interval.tv_sec = 0;
value.it_interval.tv_nsec = 0;
timer_settime (gTimerid, 0, &value, NULL);
}
void timer_callback(int sig)
{
printf(" Catched timer signal: %d ... !!\n", sig);
}
int main(int ac, char **av)
{
(void) signal(SIGALRM, timer_callback);
start_timer();
while(1);
}
On Linux and other POSIX systems, timer_create is the function you're looking for. Set the timer to be delivered via a signal and it will be very reliable. Don't use the older ualarm or setitimer apis which are deprecated and have various ugly issues that you probably don't want to get into unless you're already an expert on realtime unix stuff...
You have two options to call a function every other second:
Do a "busy wait"
Make your process/thread sleep for an amount of time
The first option is definitely more accurate but a lot more CPU consumptive and less responsive. It can simply be done with a while or for loop.
Here a small example of how this busy-wait loop might look like:
#include <time.h>
#define TIME_TO_WAIT 1 /* wait for one second */
...
clock_t last = clock();
while(1) {
clock_t current = clock();
if (current >= (last + TIME_TO_WAIT * CLOCKS_PER_SEC)) {
yourSpecialFunction(); /* insert your function here */
last = current;
}
}
The second option is maybe less accurate (since your process may wait a little less or more than the specified time) but it is the preferred option in terms of multiprocessing and scheduling. You can use your systems sleep()/usleep()/Sleep() (depends on your system) function for it. Alternatively you can use signals.
ualarm() is probably the simplest way of doing this. As others have mentioned, perfect accuracy isn't guaranteed, but the resolution is likely sufficient.
void each_sec(int x)
{
printf("%d", (int)time(NULL));
}
int main()
{
signal(SIGALRM, each_sec);
ualarm(1000000, 1000000);
}
I used signal for clarity, but sigaction/sigprocmask is more portable and featureful.
on Unix/Linux, you can use a timer, here's an example:
#include <stdio.h>
#include <signal.h>
#include <sys/time.h>
int limit = 10;
/* signal process */
void timeout_info(int signo)
{
if(limit == 0)
{
printf("Sorry, time limit reached.\n");
exit(0);
}
printf("only %d senconds left.\n", limit--);
}
/* init sigaction */
void init_sigaction(void)
{
struct sigaction act;
act.sa_handler = timeout_info;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
sigaction(SIGPROF, &act, NULL);
}
/* init */
void init_time(void)
{
struct itimerval val;
val.it_value.tv_sec = 1;
val.it_value.tv_usec = 0;
val.it_interval = val.it_value;
setitimer(ITIMER_PROF, &val, NULL);
}
int main(void)
{
char *str;
char c;
init_sigaction();
init_time();
printf("You have only 10 seconds for thinking.\n");
while(1);
exit(0);
}
substitute your own function for timeout_info
On Linux it is very common to use select() for timing. This way you can also be notified about file descriptors activity.
You need to have a struct timeval for interval and pass it as the last argument of select.