Re: Timer
"siska" <stephenwvickers@hotmail.com> writes:
Keith Thompson wrote:
[...]
Sleeping for a specified number of seconds is one of those things that
can be done much better using non-portable code. Most systems will
provide something like a sleep() function.
[...]
Thank you for quoting context in spite of the Google Groups interface.
But it's seldom necessary to quote the entire article to which you're
replying. Please trim anything that's not relevant to your reply. In
particular, don't quote signatures unless you're commenting on them.
I use this sometimes when writing short programs for
AIX/HPUX/Linux/Solaris and Windows, I define "WIN32" when compiling on
Windows (cl ... /D"WIN32 ..."):
***CODE EXAMPLE***
/* file to include - in whatever file it is needed */
#ifdef WIN32
#include <windows.h>
#else /* WIN32 */
#include <unistd.h>
#endif /* WIN32 */
...
/* define the function to use */
#ifdef WIN32
#define SLEEP_TIME 5000
#define SLEEP_FUNC Sleep
#else /* WIN32 */
#define SLEEP_TIME 5
#define SLEEP_FUNC sleep
#endif /* WIN32 */
...
/* someone deep in the code the function is used */
if( wait_for_something == true )
{
SLEEP_FUNC ( SLEEP_TIME );
}
***CODE EXAMPLE***
Of course this may not be the safest or best way to do it but it works
for simple programs.
That will work (I presume) if you happen to compile your program on a
Windows or Unix-like system. It's not portable to any other systems,
so it's off-topic here.
Also, why do you write
if( wait_for_something == true )
? Where is the identifier "true" defined? If you're using C99, it's
in <stdbool.h>; if you're using C++, it's keyword, but C++ is
off-topic here in comp.lang.c. (I just noticed that this is
cross-posted to comp.lang.c and comp.lang.c++; that's hardly ever a
good idea.)
If a variable represents a condition, it's far better to use it
directly as a condition:
if (wait_for_something)
{
...
}
Consider what happens if wait_for_something is an int with a value
other than 0 or 1.
And if you think that "wait_for_something == true" is clearer than
"wait_for_something", wouldn't "(wait_for_something == true) == true"
be better yet?
See section 9 of the comp.lang.c FAQ, <http://www.c-faq.com/>.
--
Keith Thompson (The_Other_Keith) kst-u@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.