CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 2 of 3 FirstFirst 123 LastLast
Results 16 to 30 of 36

Thread: Problem With Sleep() When drawing ananalog clock

  1. #16
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,144

    Re: Problem With Sleep() When drawing ananalog clock

    As your code doesn't explicitly use a message pump, I would be looking to use CreateTimerQueueTimer() to execute a callback function periodically.

    See http://msdn.microsoft.com/en-us/libr...=vs.85%29.aspx



    But in the context of the exercise being asked, I would suggest that the accuracy of the clock is not the most important factor. I would suggest something like this as part of main()
    Code:
    repeat
    {
         get time
         show time
         sleep 1 second
    }
    You have a clock class that has functions to
    display the clock face
    display the given time
    Last edited by 2kaud; January 20th, 2015 at 03:49 PM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.6.3)

  2. #17
    Join Date
    May 2014
    Posts
    72

    Re: Problem With Sleep() When drawing ananalog clock

    I can't understand that msdn examples

  3. #18
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,144

    Re: Problem With Sleep() When drawing ananalog clock

    This is one way that the time can be obtained to be displayed. This example will just display the time in the console every second.

    Code:
    #include <iostream>
    #include <chrono>
    #include <Windows.h>
    using namespace std;
    using namespace std::chrono;
    
    const int interval = 1000;
    
    VOID CALLBACK TimerRoutine(PVOID lpParam, BOOLEAN TimerOrWaitFired)
    {
    time_t tt(steady_clock::to_time_t(steady_clock::now()));
    struct tm *tim(localtime(&tt));
    
    	//Display the time here
    	cout << tim->tm_hour << ":" << tim->tm_min << ":" << tim->tm_sec << endl;
    }
    
    int main()
    {
    HANDLE hTimer = NULL;
    
    	if (!CreateTimerQueueTimer(&hTimer, NULL, (WAITORTIMERCALLBACK)TimerRoutine, (PVOID)NULL, 0, interval, WT_EXECUTEDEFAULT)) {
    		cout << "Cannot create timer! - error: " << GetLastError() << endl;
    		return 1;
    	}
    
    	WaitForSingleObject(GetCurrentProcess(), INFINITE);
    }
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.6.3)

  4. #19
    Join Date
    May 2014
    Posts
    72

    Re: Problem With Sleep() When drawing ananalog clock

    Thank you very much for your code.
    But it's really beyond the scope the lessons I have been taught!
    Please look, I'm at chapter 16 of that book. The pointers are in next chapter. And those material that you have used them in that code are advanced.

    Anyway, thanks again.

  5. #20
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    4,626

    Re: Problem With Sleep() When drawing ananalog clock

    Quote Originally Posted by GCDEF View Post
    Not really. What's being said is that sleep will work, but it's not good programming practice.
    Nope, what I meant is that it won't work...
    There is time going into the code to draw the hands
    a Sleep(X) will not give you an EXACT X amount of sleep, it'll be as close as the system can give you, but it will likely be a bit more because it may take some time for your thread to get a timeslice allocated to it.
    It could also be slightly shorter than X, although that's a rare occurrence.
    On top of that, for a GUI type app, as others have said, Sleep just blocks your UI and so it won't even visually paint anything.


    You'd be better to have a timer fire every second to update your clock
    Even timers aren't precise enough to try and make a clock accumulation. You NEED to query the system clock to get an accurate time and display that.
    you also want your timer faster than the displaye dincrement or it might run up to a second slow, and (even if there's no timeslice issues) may occasionally leap over a second.

    It's not unlike the theory of sampling data, you want your sampling data to be at least 2x your highest capturable frequency.

    Applied here, you want your timer at least 2x faster than the shortest displayfrequency (or display increment).

    If you want a 'smooth' clock, you'll want it 5-20x faster than the tick. much more than that won't make a very noticable visual difference anymore.

  6. #21
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    4,626

    Re: Problem With Sleep() When drawing ananalog clock

    Quote Originally Posted by abbassi View Post
    What I got from your reply were:
    1- Solving the exercise by the materials it has said is not possible. And it's the author's mistake that has had that question. Am I right?
    2- I need to use of a C++ timer rather than clock() and/or Sleep(). And there isn't any function named sleep(). What the author has mentioned.
    1)
    No, I said that the apparent method in the OP will make a clock that shows something looking like time, but it'll acumulate small errors and eventually be off by several seconds.
    For an educational exercise, this might be acceptable. (it still makes it sort of a "bad" programming task, but I've seen a lot worse)

    You may be able to get something to work 'accurately' with
    while not end
    {
    get time
    display time
    wait 1 sec
    }

    But that depends a bit on the framework you're using, as others said, a Sleep() will typically "freeze" the UI into doing anything, including displaying itself to screen.

    For a console app, this work because the display part of the console is displayed independant of the console buffer
    for some frameworks it'll work becaus eyou paint to a buffer, and the buffer is independantly updated to screen.
    for something like MFC, Qt or the plain SDK/API, it'l freeze the UI, unless you provide background painting yourself.


    2)
    C++ does not have such a thing as "timers" so "c++ timers" don't exist.
    when we talk about timers, we're talking about windows timers, which assumes you're compiling for Windows (and not mac or Linux or whatever) and that you have a GUI app.

  7. #22
    Join Date
    May 2014
    Posts
    72

    Re: Problem With Sleep() When drawing ananalog clock

    OK guys. Thank you very much. But I still have one question:
    Is there a possible way just using the materials that are taught in the book (until here, chapter 16) and also using sleep()/Sleep() and clock() as the exercise itself says, for resolving the exercise please?
    The book as I mentioned is this: http://books.google.com/books?id=We2...epage&q&f=true

  8. #23
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,302

    Re: Problem With Sleep() When drawing ananalog clock

    Quote Originally Posted by abbassi View Post
    OK guys. Thank you very much. But I still have one question:
    Is there a possible way just using the materials that are taught in the book (until here, chapter 16) and also using sleep()/Sleep() and clock() as the exercise itself says, for resolving the exercise please?
    The book as I mentioned is this: http://books.google.com/books?id=We2...epage&q&f=true
    One problem that we have (without reading the whole book) is knowing what type of sample code is included in the book. So when exercise 6) states: 'Make an "analog clock," that is, a clock with hands that move' we have no way of knowing if previous chapters have introduced some sort of graphical library and/or have shown you techniques that allow you to draw a clock with hands on the screen. Getting the system time and pausing (using clock() and sleep() or something else) is the trivial part. The hard part would be to display the analog clock without a library or without the book showing you how to do this without a library.

    If the book hasn't supplied a library, I would recommend you to forget the analog clock approach and simply create a console app that displays the time. For the exercise, I would have a loop that reads the system time and store the hour, minute and second values into 3 variables. Inside the loop, I would use a sleep with a 100 millisecond wait. Each time through the loop I would get the system time, extract the hour, minute and second values into temporary variables. I would then compare them with the 3 original values - if anyone have changed, I would write the new time out to the console.

  9. #24
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,144

    Re: Problem With Sleep() When drawing ananalog clock

    The book is Stroustrup's Programming Principles and Practice Using c++ It does use its own graphics library which is available as a download from the authors site and is based upon FLTK. Chapter 16 is the last chapter in the graphics section.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.6.3)

  10. #25
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,302

    Re: Problem With Sleep() When drawing ananalog clock

    Quote Originally Posted by 2kaud View Post
    The book is Stroustrup's Programming Principles and Practice Using c++ It does use its own graphics library which is available as a download from the authors site and is based upon FLTK. Chapter 16 is the last chapter in the graphics section.
    Fantastic. The OP probably needs to jump back a few chapters to get how to use the graphics library.

  11. #26
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,588

    Re: Problem With Sleep() When drawing ananalog clock

    Quote Originally Posted by OReubens View Post
    Nope, what I meant is that it won't work...
    There is time going into the code to draw the hands
    a Sleep(X) will not give you an EXACT X amount of sleep, it'll be as close as the system can give you, but it will likely be a bit more because it may take some time for your thread to get a timeslice allocated to it.
    It could also be slightly shorter than X, although that's a rare occurrence.
    On top of that, for a GUI type app, as others have said, Sleep just blocks your UI and so it won't even visually paint anything.



    Even timers aren't precise enough to try and make a clock accumulation. You NEED to query the system clock to get an accurate time and display that.
    you also want your timer faster than the displaye dincrement or it might run up to a second slow, and (even if there's no timeslice issues) may occasionally leap over a second.

    It's not unlike the theory of sampling data, you want your sampling data to be at least 2x your highest capturable frequency.

    Applied here, you want your timer at least 2x faster than the shortest displayfrequency (or display increment).

    If you want a 'smooth' clock, you'll want it 5-20x faster than the tick. much more than that won't make a very noticable visual difference anymore.
    I think we need to keep in mind that this is an academic exercise. I don't think it really matters if it's not entirely accurate. Given that sleep will block the thread for approximately the specified amount of time, and knowing that it will run a bit slow because of overhead of other calls, it will achieve what it needs to.

  12. #27
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,588

    Re: Problem With Sleep() When drawing ananalog clock

    Quote Originally Posted by abbassi View Post
    OK guys. Thank you very much. But I still have one question:
    Is there a possible way just using the materials that are taught in the book (until here, chapter 16) and also using sleep()/Sleep() and clock() as the exercise itself says, for resolving the exercise please?
    The book as I mentioned is this: http://books.google.com/books?id=We2...epage&q&f=true
    Yes. It won't be accurate and as I've said several times, and others have intimated, you'll need a loop.

    Get time
    Display time
    Sleep
    Repeat

  13. #28
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,144

    Re: Problem With Sleep() When drawing ananalog clock

    Quote Originally Posted by Arjay View Post
    Fantastic. The OP probably needs to jump back a few chapters to get how to use the graphics library.
    The code posted by the OP in post #1 uses the graphics library - the problem as explained was that the code uses Sleep(1000) but the program goes into a 'comma' at that statement.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.6.3)

  14. #29
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: Problem With Sleep() When drawing ananalog clock

    Quote Originally Posted by abbassi View Post
    OK guys. Thank you very much. But I still have one question:
    Is there a possible way just using the materials that are taught in the book (until here, chapter 16) and also using sleep()/Sleep() and clock() as the exercise itself says, for resolving the exercise please?
    The book as I mentioned is this: http://books.google.com/books?id=We2...epage&q&f=true
    Don't know if threads are covered in the book, but a quick way to make the program update approximately each second is to run the loop in a thread.
    Code:
    std::atomic<bool> stop(false);
    std::thread([&stop]() {
        while (!stop) {
            // tell GUI to redraw
            Sleep(1000); // 1s
        }
    }).detach();
    Fl_Widget provides a member function redraw(), but I couldn't find out if it can be called from a worker thread.
    Last edited by D_Drmmr; January 21st, 2015 at 03:39 PM.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  15. #30
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,302

    Re: Problem With Sleep() When drawing ananalog clock

    Quote Originally Posted by 2kaud View Post
    The code posted by the OP in post #1 uses the graphics library - the problem as explained was that the code uses Sleep(1000) but the program goes into a 'comma' at that statement.
    Reduce the sleep time and pump messages inside the loop. Use a timer. Use a thread. Handle onIdle processing. Lot's of ways to skin this cat.

Page 2 of 3 FirstFirst 123 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)