I want to refresh and have control of time interval changes. Most people only have an infinite loop constantly polling the time from time.h and wasting cycles. There is a way to get clock changes without disturbing too much the system? I am using c/c++ and really want to learn how to do this manually only using linux libraries. Most programs need the notion of time.
I want to be notified of system clock updates. I am trying to do a scientific app that responds in real time. Sleep() and thing like that only let me specify a time delay starting from the execution of that statemen. Localtime() and string returning times from the c header only give me the specific time when was executed. If I use it this time is too late, it had elapsed too many nanoseconds.
Read the time(7) man pages to understand how to use the system calls gettimeofday(2), setitimer(2), clock_gettime(2), timer_create(2) etc... and library functions (strftime, localtime, ...) related to time.
If you want to code an application recieving timer events, learn about timers and e.g. SIGALRM signal. Read first signal(7)
But you really should read e.g. Advanced Unix Programming and Advanced Linux Programming and understand what are syscalls
You might want to use poll(2) for polling or for waiting.
The most basic approach that's also portable and compatible with most other tasks is select. It sleeps until a certain amount of time elapses or a file becomes ready for I/O, which gives you a way to update the task list before the next task occurs. If you don't need interruption capability, you can just use sleep (or usleep).
Related
I am currently working on a program that must do some work regularly. At the moment I using the following construction:
int main(int argn, char** argv) {
for(;;) {
//Do work - the programm spends 5-8ms here
nanosleep(...); //Sleep 10ms
}
return 0;
}
The problem is: One loop execution should always last 10ms. Because of the high amount of time spend in the working part of the loop I can't sleep simply sleep for 10ms...
A solution might be measuring the time spend on work with clock_gettime() and adjust the nanosleep() accordingly. But I am not happy with this solution, because it's very easy to place code outside the area that's measured...
I have searched the internet for alternatives, I found the three calls:
timer_create
getitimer
alarm
timerfd_create
It's okay if the solution is not portable to Windows or other operating systems.
But I am not sure which solutions fits best to my problem. Any advice or suggestions? What are the pros and cons with the 4 alternatives I mentioned?
EDIT: There is also another problem with this solution: If i get the documentation right, the nanosleep syscall put the process into sleep for at least 10ms, but it can take longer if the system is under load... Is there any way to optimize that?
EDIT2: For your information: In the do work part a network request is made to a another device on the network (a microcontroller or a PLC that is able to answer the request in time). The result is being processed and send back to the device. I know Linux is not a realtime OS and not optimal for this kind of task... It's no problem if the solution is not perfect realtime, but it would be nice to get as much realtime as possible.
Check the time right before the call to nanosleep and compute how long to sleep right there. There will be no need to measure any code. Just note the time you return from nanosleep and calculate how much more time you need to sleep.
Signal Handling is the most preferred way to do it .I prefer timer_create as it is posix function conforming to POSIX.1-2001. Microsoft also provides help for writing POSIX Standard Code.
Use clock_nanosleep which lets you request to sleep until a given absolute time (TIMER_ABSTIME flag) rather than taking a duration. Then you can simply increment the destination absolute time by 10ms on every iteration.
Using clock_nanosleep also allows you (if you want) to use the monotonic clock option and avoid having to deal with the possibility of the user/admin resetting the system clock while your program is running.
I have a thread running on a Linux system which i need to execute in as accurate intervals as possbile. E.g. execute once every ms.
Currently this is done by creating a timer with
timerfd_create(CLOCK_MONOTONIC, 0)
, and then passing the desired sleep time in a struct with
timerfd_settime (fd, 0, &itval, NULL);
A blocking read call is performed on this timer which halts thread execution and reports lost wakeup calls.
The problem is that at higher frequencies, the system starts loosing deadlines, even though CPU usage is below 10%. I think this is due to the scheduler not waking the thread often enough to check the blocking call. Is there a command i can use to tell the scheduler to wake the thread at certain intervals as far as it is possble?
Busy-waiting is a bad option since the system handles many other tasks.
Thank you.
You need to get RT linux*, and then increase the RT priority of the process that you want to wake up at regular intervals.
Other then that, I do not see problems in your code, and if your process is not getting blocked, it should work fine.
(*) RT linux - an os with some real time scheduling patches applied.
One way to reduce scheduler latency is to run your process using the realtime scheduler such as SCHED_FIFO. See sched_setscheduler .
This will generally improve latency a lot, but still theres little guarantee, to further reduce latency spikes, you'll need to move to the realtime brance of linux, or a realtime OS such as VxWorks, RTEMS or QNX.
You won't be able to do what you want unless you run it on an actual "Real Time OS".
If this is only Linux for x86 system I would choose HPET timer. I think all modern PCs has this hardware timer build in and it is very, very accurate. I allow you to define callback that will be called every millisecond and in this callback you can do your calculations (if they are simple) or just trigger other thread work using some synchronization object (conditional variable for example)
Here is some example how to use this timer http://blog.fpmurphy.com/2009/07/linux-hpet-support.html
Along with other advice such as setting the scheduling class to SCHED_FIFO, you will need to use a Linux kernel compiled with a high enough tick rate that it can meet your deadline.
For example, a kernel compiled with CONFIG_HZ of 100 or 250 Hz (timer interrupts per second) can never respond to timer events faster than that.
You must also set your timer to be just a little bit faster than you actually need, because timers are allowed to go beyond their requested time but never expire early, this will give you better results. If you need 1 ms, then I'd recommend asking for 999 us instead.
I just realized that after learning a lot about various scheduling algorithms, how a context switch is done, etc. one thing still isn't clear to me.
Take a uniprocessor system:
If process A is running and it's time slot should end in 5 seconds, how does the scheduler or the operating system know how to end it after 5 seconds? No part of the operating system can run while A is running. The scheduler is supposed to be monitoring it, but how can it if it cannot run? Does the operating system's scheduler write an ISR and have an interrupt generate every 5 seconds? Is this possible? Even if it is, it doesn't seem a good way to implement it.
How exactly does a scheduler do this?
Does the operating system's scheduler write an ISR and have an interrupt generate every 5 seconds? Is this possible? Even if it is, it doesn't seem a good way to implement it.
Yes, this is exactly how it works on a preemptive multitasking system (although on desktop systems the interval is usually more like 10 milliseconds).
Yes, there are other schemes, such as cooperative multitasking, where each process decides for itself when to yield.
Yes, normally there is some kind of timer interrupt that fires. The kernel can then run for a bit and switch process context if it needs to - normally that interrupt would fire an awful lot more often than just once every 5 seconds though. Why doesn't it seem like a good way to implement it?
I am working on a threaded application on Linux in C++ which attempts to be real time, doing an action on a heartbeat, or as close to it as possible.
In practice, I find the OS is swapping out my thread and causing delays of up to a tenth of a second while it is switched out, causing the heartbeat to be irregular.
Is there a way my thread can hint to the OS that now is a good time to context switch it out? I could make this call right after doing a heartbeat, and thus minimize the delay due to an ill timed context switch.
It is hard to say what the main problem is in your case, but it is most certainly not something that can be corrected with a call to sched_yield() or pthread_yield(). The only well-defined use for yielding, in Linux, is to allow a different ready thread to preempt the currently CPU-bound running thread at the same priority on the same CPU under SCHED_FIFO scheduling policy. Which is a poor design decision in almost all cases.
If you're serious about your goal of "attempting to be real-time" in Linux, then first of all, you should be using a real-time sched_setscheduler setting (SCHED_FIFO or SCHED_RR, FIFO preferred).
Second, get the full preemption patch for Linux (from kernel.org if your distro does not supply one. It will also give you the ability to reschedule device driver threads and to execute your thread higher than, say, hard disk or ethernet driver threads.
Third, see RTWiki and other resources for more hints on how to design and set up a real-time application.
This should be enough to get you under 10 microseconds response time, regardless of system load on any decent desktop system. I have an embedded system where I only squeeze out 60 us response idle and 150 us under heavy disk/system load, but it's still orders of magnitude faster than what you're describing.
You can tell the current executing thread to pause execution with various commands such as yield.
Just telling the thread to pause is non-determanistic, 999 times it might provide good intervals and 1 time it doesn't.
You'll will probably want to look at real time scheduling for consistant results. This site http://www2.net.in.tum.de/~gregor/docs/pthread-scheduling.html seems to be a good starting spot for researching about thread scheduling.
use sched_yield
And fur threads there is an pthread_yield http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_yield.3.html
I'm a bit confused by the question. If your program is just waiting on a periodic heartbeat and then doing some work, then the OS should know to schedule other things when you go back to waiting on the heartbeat.
You aren't spinning on a flag to get your "heartbeat" are you?
You are using a timer function such as setitimer(), right? RIGHT???
If not, then you are doing it all wrong.
You may need to specify a timer interval that is just a little shorter than what you really need. If you are using a real-time scheduler priority and a timer, your process will almost always be woken up on time.
I would say always on time, but Linux isn't a perfect real-time OS yet.
I'm not too sure for Linux, but on Windows it's been explained that you can't ask the system to not interrupt you for several reasons (first paragraph mostly). Off my head, one of the reasons is hardware interrupts that can occur at any time and over which you have no control.
EDIT Some guy just suggested the use of sched_yield then deleted his answer. It'll relinquish time for your whole process though. You can also use sched_setscheduler to hint the kernel about what you need.
What is the simplest way to write a timer in C/C++?
Hi,
What is the simplest way to write a timer, say in C/C++? Previously I used a for loop and a do-while loop. I used the for loop as a counter and the do-while loop as a comparison for "end of time". The program worked as I wanted it to, but consumed too much system resources.
I'm looking for the simplest way to write a timer.
Thank you!
EDIT:
The program works on a set of servers both Linux and Windows, so it's a multiplatform environment. I dont want to use the unsleep or sleep function as I'm trying to write everything from scratch.
The nature of the program: The program counts power time and battery time on systems.
EDIT2:
OK, it seems that this caused some confusion so I'm going to try to explain what I have done so far. I've created a program that runs in the background and powers off the system if it's idle for a certain amount of time, it also checks for the battery life on a specific system and goes to stand by mode if the system has been running on battery for a while. I input the time manually so I need a timer. I want to write it from scratch as it's a part of a personal project I've been working on.
Your best bet is to use an operating system primitive that suspends the program for a given amount of time (like Sleep() in Windows). The environment where the program will run will most likely have some mechanism for doing this or similar thing. That's the only way to avoid polling and consuming CPU time.
If you just want your program to wait a certain amount of time, you can use:
Sleep (in Windows)
usleep (in Unix)
boost::this_thread::sleep (everywhere)
If you wish to process or display the time going up until elapsed, your approach of using a while() loop is fine, but you should add a small sleep (20ms, for example, but ultimately that depends on the precision you require) in the while loop, as not to hog the CPU.
There are two ways:
One. Write your own timer which wraps the platform specific command. And stick to using it.
e.g.
void MySleep::Sleep(int milliSec)
{
#ifdef WIN32
sleep(milliSec) ;
#else
#ifdef LINUX
usleep(milliSec*1000); //microseconds
#endif
#endif
}
Two. Choose libraries and toolkits that support all your target platforms. Toolkits like Qt and boost can be used to cover up platform specific goo.
Both boost and Qt have timers with high functionality and are extensible. I recommend you look them up.
http://linux.die.net/man/2/alarm
Description:
alarm() arranges for a SIGALRM signal to be delivered to the process in seconds seconds.
and use cygwin on windows.
What you're already doing is the easiest.
It consumes too much CPU because it's going hard out doing your check (is timer expired?)
or whatever.
To fix that put usleep(1) or whatever the OS equivalent of a very short sleep in that main
loop and you'll have what you need.
You didn't mention the environment you're building a timer in. For example, microcontrollers usually have a timer/counter unit that raise interrupts at some intervals by counting the clock cycles and you can just handle their interrupts.
use a sleep function.. and a function pointer
using sleep function doesnt consume processor time... You can use the function pointer to notify when the timer expired. if you dont need events you can simply use sleep/delay function
Edit do what smallduck has suggested. using macros for currectly calling the approperiate operating system call (if you want to avoid using boost)... using anything else then timer wont be accurate.
You can call time() multiple times and compare the values.
#include <time.h>
int main ()
{
time_t start_time;
time_t current_time;
start_time = time(NULL);
current_time = time(NULL)
while (current_time < start_time + TIMEOUT)
{
/* Do what you want while you're waiting for the timeout */
current_time = time(NULL);
}
...
}
The advantage over sleep() is that you can still execute code while you are waiting. For example... polling for an external stop signal, etc.
A lot of these answers include something known as "busy waiting." Checking the time over and over again in a while() loop is a bad idea 99% of the time.
I think you may want to step back and approach the problem a bit differently.
It sounds like you want a program to turn something off under a given set of conditions.
So you have a few options. You can "wake up" your background program every so often and check if conditions are met (using sleep / usleep, which are standard functions in all languages on all operating systems).
Or you can background the process indefinitely, until some type of event occurs. This would probably best be accomplished in C via signals or some type of wait function.
Its hard to tell exactly what you want, because its hard to tell how your standby / turn off conditions are met and how they are triggered.
You may want your battery monitor program to do some type of IPC or maybe write some type of dummy file to a known directory when it needs to standby. With IPC, you can use some type of wait() function that activates when a signal or IPC is sent to your background process. With the file method, you could sleep(), and check for that files existence every wake-up.
You could also easily use networking / sockets to do this as well. Listen on the loopback interface (127.0.0.1) and on a predefined port. Now wait until data comes in on that socket. When the battery monitor needs to standby, he sends a simple message via loopback to your new process. This will use effectively 0 cpu.
There are probably other ways as well, but I think that should give you a general idea.
It is not a trivial task because, depending on your requirements, it can be quite complex.
The problem with timers is that if you want a good timer you may need to move beyond C++/C into the realm of OS calls causing you to end up with a OS-specific solution or use some library like boost to wrap it.
I mainly program in Windows so my advice come from that realm:
In Windows you can of course use a timer(NULL) as some suggested; however mostly when you are waiting you don't want to bog down the CPU with a loop. Using sleep is one way but instead I usually take the approach of using an object to wait for. Either the object signals or a timeout occurs. E.g. in order to wait for 10 seconds:
res = WaitForSingleObject( someobjecthandle, 10000 );
if the return value is timeout I know I waited 10s, otherwise the object signaled in some way and I didn't wait 10s. Now using that you can create an effective timer.
Another approach which is a bit more work is to create a separate timer thread (Windows again) which periodically sends a message to your message loop.
A third approach is to create a thread that is the actual timer, you start the thread with an argument, the thread sleeps this time (I know you don't want to use that but you can use another MsgWaitForMultipleObjects function inside the thread to react if you want to kill the timer prematurely) and do a WaitForSingleObject on the handle of the thread, when it signals the time is up (or a timeout).
There are more ways to do this, but these are some starting points.
If all you need is a code snippet that lets your program rest, a call to sleep is enough (if you're OK with second granularity).
If you need to run multiple timers with a single thread then maintaining a hash table holding active timers is a very good method. You use the expiry time to form the hash key. Each timer tick you then search the hash table for timers which have expired.
You could always play around with threads. One master thread could be scheduling tasks/jobs to be carried out at certain intervals. But then we are into the area of scheduling, which is something that the OS does. So as GMan said, you're suddenly in the realm of developing your own OS, or mimicing parts of the OS functionality.
void SimpleTimer(int timeinterval)
{
int starttime, currenttime, difference;
starttime = time(null);
do
{
currenttime = time(null);
difference = currenttime - starttime;
}
while (difference < timeinterval);
}