Thread: Clock

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    6

    Clock

    Out of curiosity, how do you write a program that takes an action every second? Or every half second?

    Do you just get access to the system time and run a while(1) loop and keep on checking?

    Thanks.

  2. #2
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    Yes and no, it's not a good idea to stay in a loop wasting the CPU.

    At least two common ways I know of,
    1. use sleep() (unix) or Sleep() (Win32)
    2. Use some sort of timer API provided by the system (Ie, Windows Timers)
    Last edited by zacs7; 06-01-2008 at 10:40 PM.

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Note also that you may want to sleep for less than 1 second, otherwise you may find that you drift [1]. Also, if you are showing the time in some form, make sure you ask the OS what time it each time you update the time. Sleeping for 0.1s (100 milliseconds) and checking to see if the time (in seconds) has changed would do the task.

    The extra overhead shouldn't make much of a difference.

    [1] Since the OS will guarantee that it sleeps of AT LEAST the time specified, and you may find that it sleeps for, say, 10 milliseconds more than what you specified. If you then do some processing (such as writing the time to a window or console display), and then sleep again, you will eventually get out of sync with the actual time.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by matsp View Post
    [1] Since the OS will guarantee that it sleeps of AT LEAST the time specified, and you may find that it sleeps for, say, 10 milliseconds more than what you specified. If you then do some processing (such as writing the time to a window or console display), and then sleep again, you will eventually get out of sync with the actual time.
    That's not true.
    Windows's Sleep function can sleep less than the specified interval, too.
    But if you need precise timing, say 60 times over a second, then I have exactly what you need.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #5
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    Who said he was talking about Windows?

    Quote Originally Posted by man sleep
    ...
    The sleep instruction suspends the calling process for at least the specified number of seconds
    ...

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by Elysia View Post
    That's not true.
    Windows's Sleep function can sleep less than the specified interval, too.
    Ok, fair point, it should say "May not sleep the exact amount you asked for". And even if the sleep operation itself _IS_ precise, the scheduler in the OS may well think that there are other more important tasks to run at the time when the process becomes runnable, so it may not be run until "some time later" - so it's fine to sleep, but relying on the amount of time it actually sleeps is not going to work, whether it rounds the sleep time down or up, and whether your process is the only one or not, it will sooner or later drift out of sync if you rely on the timing from operations that put the process to sleep. You still need to read the system time (at least every now and again - and it's just more logic to do it often, and system time is one of the functions in the OS that is highly optimized).

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  7. #7
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Quote Originally Posted by Elysia View Post
    I have exactly what you need.
    where?
    Mainframe assembler programmer by trade. C coder when I can.

  8. #8
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by matsp View Post
    Ok, fair point, it should say "May not sleep the exact amount you asked for". And even if the sleep operation itself _IS_ precise, the scheduler in the OS may well think that there are other more important tasks to run at the time when the process becomes runnable, so it may not be run until "some time later" - so it's fine to sleep, but relying on the amount of time it actually sleeps is not going to work, whether it rounds the sleep time down or up, and whether your process is the only one or not, it will sooner or later drift out of sync if you rely on the timing from operations that put the process to sleep. You still need to read the system time (at least every now and again - and it's just more logic to do it often, and system time is one of the functions in the OS that is highly optimized).
    Oh, absolutely. To this I agree.

    Quote Originally Posted by Todd Burch View Post
    where?
    I have code that does exactly this, but no one has asked for it.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  9. #9
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Elysia, can I have you code that properly sets a timer, pretty please with sugar on top? (unless you are a diabetic or on a diet, then you get the artificial sweetener, unless you are into health food and aren't into the long term effects of poisons in your body, then I'll just put an apple on top, but be sure to peel it before eating so you don't inject the 27+ pesticides found in the skin...)
    Mainframe assembler programmer by trade. C coder when I can.

  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Originally for C++, this should allow it to work for C:
    Code:
    	typedef void (Callback*)();
    	void Synchronize(const UINT64 dwTimeFrame, const UINT64 dwFramesPerTimeFrame, Callback* pCallback)//CCallback& rCallback)
    	{
    		const UINT64 dwTickRate = dwTimeFrame / dwFramesPerTimeFrame; // Calculate amount of time to sleep each time
    		INT32 nSleepNeeded; // Stores the amount of time we need to sleep
    		UINT64 dwTimeElapsed; // Time elapsed since beginning of time frame
    		UINT64 dwNextSleepBoundary; // The next "target" time to sleep until.
    		DWORD dwTick; // Used to hold a snapshot of timeGetTime so we can calculate elapsed time
    		DWORD dwTick2 = timeGetTime(); // Snapshot of the beginning of the code sample
    
    		// Initialize variables
    		nSleepNeeded = 0;
    		dwTimeElapsed = 0;
    		dwNextSleepBoundary = dwTickRate; // Set the next sleep boundary to the next tick.
    		dwTick = timeGetTime(); // Get a snapshot of the current time
    		while (dwNextSleepBoundary <= dwTimeFrame)
    		{
    			//rCallback.DoCallback();
    			pCallback();
    			dwTimeElapsed = timeGetTime() - dwTick; // Calculate elapsed time
    			INT64 nTemp = dwNextSleepBoundary - dwTimeElapsed; // Calculate amount of time we need to sleep (at least)
    			ASSERT(nTemp <= 0xFFFFFFFF); // Must not exceed the precision of a UINT32
    			if (nTemp > 0) // Safesty check; we don't want to do Sleep(0) or sleep a negative value since Sleep takes a DWORD
    			{
    				nSleepNeeded = (UINT32)nTemp;
    				Sleep(nSleepNeeded); // Sleep for the amount of time necessary before next drawing
    			}
    			dwNextSleepBoundary += dwTickRate; // Increase sleep "boundary" to next time frame tick
    		}
    	}
    Basically the arguments are - the time you wish it to tun and how many times in that time period you want it to callback [in ms] (eg, 1000, 60 - 60 times per second).
    This is for Windows, we have yet to hear what OS the OP is using.

    Quote Originally Posted by zacs7 View Post
    Who said he was talking about Windows?
    Remember that mats used the word "OS", but Windows's Sleep function does not sleep for at least, but rather approximately the amount specified. Or in other words, don't rely on the sleep function to sleep at least the number of time units specified; instead count on it sleeping approximately the number of time units specified.
    Last edited by Elysia; 06-02-2008 at 08:19 AM.

  11. #11
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Thank You!!
    Mainframe assembler programmer by trade. C coder when I can.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Logical Error in Clock program
    By SVXX in forum C++ Programming
    Replies: 0
    Last Post: 05-10-2009, 12:12 AM
  2. Outside influences on clock cycles? (clock_t)
    By rsgysel in forum C Programming
    Replies: 4
    Last Post: 01-08-2009, 06:15 PM
  3. Clock Troubles
    By _Nate_ in forum C Programming
    Replies: 22
    Last Post: 06-19-2008, 05:15 AM
  4. clock program
    By bazzano in forum C Programming
    Replies: 3
    Last Post: 03-30-2007, 10:12 PM
  5. using clock()
    By sl4nted in forum C Programming
    Replies: 8
    Last Post: 11-09-2006, 07:16 PM