TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: NEIL HELLER
from: JERRY COFFIN
date: 1997-05-12 11:37:00
subject: timer() and difftime()

On (10 May 97) Neil Heller wrote to All...
 NH> I was mucking around and came across the following.  Given the
 NH> following function:
 NH> void CTimerDlg::OnStart()
 NH> {
 NH>     time_t  start, end;
 NH>     start = time(NULL);
 NH>     do {
 NH>         end = time(NULL);
 NH>     } while (difftime(end, start) < 60.0);
 NH>     AfxMessageBox("Time's up");
 NH> }
 NH> This function would work as expected (that is, the message box would
 NH> pop-up 60 seconds after the "start" was pushed) when compiled as a
 NH> 32-bit app. in MSVC 5.0.  However, when compiled as a 16-bit app. in
 NH> MSVC 1.5, this loop would time out in 30 - 40 seconds.  The tests were
 NH> run on a 90 mHz Pentium.  Does anybody have an idea?
I'd _strongly_ advise doing this considerably differently.  I'd use
something more like:
void CALLBACK TimerProc(HWND wnd, UINT, UINT timer, DWORD) {
    KillTimer(wnd, timer);  // The timer will continue to fire
                            // every minute unless we kill it.
    AfxMessageBox("Time's up");
}
void CAboutDlg::OnTimer() {
    SetTimer(
        1,                  // this identifies the timer.
        60000,              // This is the time in milliseconds
        TimerProc);         // This function will be called
}                           // when the time is up.
This has a couple of major advantages.  First of all, polling the
current time in a loop uses a lot of CPU time but doesn't accomplish
much.  Using a system timer instead allows other programs to use the CPU
time instead.  Second, using a timer allows your program to continue
processing other messages while your waiting for the time to expire.  If
you don't process other messages, your app will be completely
unresponsive, so the user won't be able to do things like move the
window around.  Worse yet, in 16 bit Windows, the user won't be able to
do anything with any other applications until the timer expires.
Finally, this will wait at least as long as you specify.  It _might_
wait a little longer if another app doesn't process its messages as
quickly as it should, but the extra delay will typically be no more than
an extra second or so.  In 16 bit Windows, there's almost no way around
this kind of situation arising though.
    Later,
    Jerry.
... The Universe is a figment of its own imagination.
--- PPoint 1.90
---------------
* Origin: Point Pointedly Pointless (1:128/166.5)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.