Sign in to follow this  
Followers 0
phil67rpg

sleep c++

19 posts in this topic

well I have looked up the sleep() command on the net but have not found an answer, all I want to know is what #include command do I use to use the sleep command. I have tried dos.h and thread but they do not work. I know this is a very simple question but like I said I have already done some research but with no luck.

1

Share this post


Link to post
Share on other sites

The sleep() function is not very accurate.  Whatever you're doing, you're probably better off using OpenGL's timer functions.

0

Share this post


Link to post
Share on other sites

The sleep() function is not very accurate.  Whatever you're doing, you're probably better off using OpenGL's timer functions.


OpenGL itself is purely a graphics library, it doesn't have timing functionality. Are you referring to glutTimerFunc, which like glut itself is deprecated?
1

Share this post


Link to post
Share on other sites

Are you referring to glutTimerFunc, which like glut itself is deprecated?

I was. I didn't realize it had been deprecated as I never work with OpenGL. I guess some other cross-platform high precision timer library then.

0

Share this post


Link to post
Share on other sites
There is no standard solution, and as above, a high precision wait is not part of c++. The language offers a low-precision wait which is OS-specific and compiler-specific, but no high precision guarantees..

Sleep, or stopping execution for a brief time, is an operating-system specific action. The granularity is fairly rough, with the best results being on a special "real time operating system", which you are not. Most OS's it is easy to ask to be suspended and then resumed at the next scheduling cycle, which may be 10, 20, 50, or more milliseconds away. On Windows specifically, Sleep() might not even wake your process at the specified update, but it may be two or three or ten updates, or maybe even longer depending on what is going on with the rest of the system.

One of the most reliable ways to get a short-term delay is by "spinning", doing an operation over and over very quickly until the time passes. This is generally not recommended, since the faster the system the more compute cycles are blocked, the more energy is wasted (particularly bad on laptops), plus the process is more likely to be demoted in priority since the task scheduler will detect it is slowing down other processes. Very reliable, but with many negative side effects.

The next most reliable is to wait for an event from something else. It can be done by firing off a delayed operation then waiting for the system to return, called a "blocking operation". Games do this all the time. One of the easiest in games is to wait for the graphics frame buffer to be flipped. Since the game can't really draw anything else until the frame is done, it works well; draw the next frame then wait. Other blocking operations are network and disk commands. Sometimes games will launch multiple tasks and have each one blocking on different things. A server might be monitoring a network pool of perhaps 50 connections, and wake either when the regular scheduler wakes it up or as an event when network data is ready on any of the connections. However, since we're not talking about real time operating systems, even these operations tend to slip toward suspending too long. You might have a reason to sleep 320 microseconds but not wake up until 15,000 microseconds have passed.

The exact commands and methods to waiting for events depend on the operating system you are using and how precise you plan on being. For games, graphics page flipping and certain network events are the typical go-to devices.
(Sorry for the accidental downvote lennylen, mouse slipped. Upvoted the other reply, which is good, and hopefully the two will cancel out. I hope the upcoming site update will allow cancelling accidental votes.)
2

Share this post


Link to post
Share on other sites

I am going to take lenny's advice and use the glutTimerfunc() I know it is deprecated but it might still work for me. I tried the windows.h and synchapi.h include files but it still does not work with the sleep() function. thanks for all the help

0

Share this post


Link to post
Share on other sites

I am going to take lenny's advice and use the glutTimerfunc() I know it is deprecated but it might still work for me. I tried the windows.h and synchapi.h include files but it still does not work with the sleep() function. thanks for all the help


if your using c++, then you should be using what Ryan_001 said, std::this_thread::sleep_for is part of the standard library since c++11. you don't need to be using an outside api for this.
0

Share this post


Link to post
Share on other sites

actually since I am working with opengl and c++ I am going to use glutTimerFunc, instead of sleep() thanks for the input.

0

Share this post


Link to post
Share on other sites

Posted (edited)

for windows -
#include <windows.h>
VOID WINAPI Sleep(DWORD Milliseconds);


for linux 
# include <unistd.h>
unsigned int sleep(unsigned int Seconds);

Notice though that they use different arguments.  In windows its in milliseconds, and in linux its in full seconds

 

In general, on windows, if you just need to keep the thread from blocking other processes, use Sleep(0);  which will immediately return control to the calling thread if no other threads or processes are waiting.  Any value higher than 0 will guarantee that control does not return to the calling thread PRIOR to that time elapsing, but there is no guarantee of it happening exactly at that time.  So e.g. Sleep (1000); would not return before 1000 milliseconds had elapsed, but it could very well not return for 5 seconds, or 5 days.  If you want to actually wait a specified time, e.g. being laptop battery friendly, you should instead use timer functions such as 

UINT_PTR WINAPI SetTimer(...);

https://msdn.microsoft.com/en-us/library/windows/desktop/ms644906(v=vs.85).aspx

 

These can have better resolution, and callback timers in specific are virtually guaranteed to execute at the specified interval except on the most heavily overloaded system.  

Edited by Cwhizard
0

Share this post


Link to post
Share on other sites

Posted (edited)

POSIX has usleep which can sleep for microseconds, although if the sleep is very short its probably just a pause loop.

If you are using a non-decade-old compiler you'll also have access to:

std::this_thread::sleep_for(std::chrono::microseconds(usec));

in C++, which will be portable.. if that means anything to you

Edited by Kaptein
1

Share this post


Link to post
Share on other sites
1 hour ago, phil67rpg said:

actually I used windows.h and it works just fine

For future reference, when you're asking a question like this, it's best to tell us what you're trying to do. You'll get much better answers that way.

0

Share this post


Link to post
Share on other sites
12 hours ago, phil67rpg said:

is there a difference between how sleep() and this_thread::sleep_for(chrono::microseconds(1000)) works?

In theory, they can share the same low-level sleeping mechanism and behave in exactly the same way, they could be completely unrelated, or they could be similar except for some details or special cases that might or might not be relevant for you.

In practice, try both and measure actual sleeping time accuracy, on every platform you care about: sleeping is important enough to deserve some testing effort.

0

Share this post


Link to post
Share on other sites
14 hours ago, phil67rpg said:

is there a difference between how sleep() and this_thread::sleep_for(chrono::microseconds(1000)) works?

https://msdn.microsoft.com/en-us/library/hh874757.aspx says: 

Quote

The implementation of steady_clock has changed to meet the C++ Standard requirements for steadiness and monotonicity. steady_clock is now based on QueryPerformanceCounter() and high_resolution_clock is now a typedef for steady_clock. As a result, in Visual C++ steady_clock::time_point is now a typedef for chrono::time_point<steady_clock>; however, this is not necessarily the case for other implementations.

Which is good because QPF is the best timer on a Windows system, is quite stable and has nanosecond precision.  If you're curious as to the details this link here: https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx.  How  exactly sleep_for() and sleep_until() are implemented, I'm not sure.

Sleep() we do know uses the internal system clock interrupt, which fires every few milliseconds (7-15ms from what I understand on most systems).

Without some benchmarking I can't say for sure, but I'm certain that sleep_for() and sleep_until() will be at least as accurate as Sleep() and possibly better.

0

Share this post


Link to post
Share on other sites

So I threw together a little test benchmark.  On my system (Windows 7, Intel i7) both sleep_for() and Sleep() were identical.

When VS (and a few other programs in the background) were open I was getting 1ms accuracy for both (+/- 10us or so).  So both performed well.  With everything closed though that number jumped up and would vary between 5ms and 15ms; but whatever the number was for sleep_for(), Sleep() was identical.  So either VS or some other program in the background was calling timeBeingPeriod(1).  It seems either way, under the hood, sleep_for() is identical to Sleep() on Windows 7 with VS 2017.

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Similar Content

    • By Strychnine
      As my title says I'm experience web developer that's been doing so for 20 years as a hobby and 10 years professionally. I dabble in tons of languages and frameworks and I'm not afraid to look at any.
      I've worked in some .NET stuff for some websites so I could probably have less learning curve with C# but I'm completely willing to work in C++ as well. In general I love programming stuff and figuring out things. Especially ones I broke. 
      Ideally I'd like to work in a team either looking to learn together or something very patient and laid back. While i'm a very good programmer in the web sense I know I will need to learn some things on the application side. So patience and a group not looking to run to steam immediately would be ideal. I've watched videos and am continuing to, but I know I always just work better hands on and sadly i'm not as artistic as I like to be.
      Thanks for your time.
      Current skill list: PHP, MySQL, Moderate C#, ReactJS, VueJS, NPM, LEMP/LAMP/IIS Server stacks(not relevant here but I understand server administration as well), as well as other stuff here and there but these are the most dominant things I work in.
    • By Shaarigan
      Dear reader,
      I'm a long time gamer, designer, developer, board game fan and hobbyist board game author, passionate in games since age of 6 with addiction to video games starting at the first own computer in the 90's. Professional developing in games industry since 2012 using the popular tools and engines as of Unreal Engine and Unity 3D to create games and optimie workflow by making tools. Highly interested in game engine development starting at the time of my bachelor studies to self improving in any topic a game engine needs to fit and above now working on my current engine project since 3 years in my rarely spread spare time seeking for a companion to contribute, helping improving existing source code on the framework base and planning/developing new features inside the framework but also on the wide tools base.
       
      About the Project
      Drough initially intended as game engine has now become a modular C++ based framework to setup and build custom game engines but could also be used for developing games in the same turn while from game developers for game developers regardless of professional, indie or hobbyist; plugging in modules improves the system with different sets of capabilities using OS low level APIs. It's partner project is my WorkBench frontend; itself also fully customizeable written in C# using C# Assemblies as plugins, providing a fully desktop integrated game development environment with state of the art but simple planned tools for both, game designers and game programmers with a code driven but node based editing masked interface. An integrated download center should help customizing the tool in the future and maybe access a users account on the website.
      Currently the framework provides:
      AI (FSM, Behavior Tree and some utilities used in machine learning) Asset support for most common file types (Bmp, Jpeg, Obj, Png, Tga), data types (Ini, Json) and packages (an own one + zip) Multithreaded task based and event system Logging and Profiler backend (file based and UDP) OpenGL 4+ Core Profile and Vulkan graphics  
      Who Contributes
      You as contributor should be a reliable consitent person with the same passion about making games and the tools used to make them as I do with a good or semi good knowledge in C++, C# and the will to invest at least a few hours per week of your spare time to help bringing the project onto the next level. "But why should I do that" would you propably ask yourself when reaching this point, so to be honest, I could not offer anything because I also just only spend time, a lot of creativity and experience into the project but I you could get part of a team working on something great getting on the edges of your knowledge and beyond.
      It would be also great to take a view on the multiplatform aspect, when you would carry some linux experience into the OS code.
       
      Getting in Touch
      When your read all the post until here, congrats! and thank you for sharing your time regardless how you decide for contributing or not. If so, I would like to get in touch, maybe with a small introduction of yourself on this thread or via PM. I would be happy about anyone to write
    • By vexe
      Greetings,
      we're making a 90s style game with prerendered backgrounds and static camera angles using a custom software-based engine (Sample WIP video)
      I was wondering what's the best way to go about setting up camera triggers. In the video I was manually switching cameras. I was thinking just OBBs (or AABBs), every camera would be associated with a bounding box, if you're in box A then camera A renders.
      - Is this a good approach or is there a better more simpler/automated way of doing it? How did old games like Resident Evil or Final Fantasy do it?
      - Doing it this way I'd have to use some sort of editor to setup the boxes. We're using Blender so I guess I could use that, although I'd prefer a more specialized editor. Is there any good 3rd party editor that's more suitable to doing this stuff? (The same editor would be used for door triggers, item/enemy spawns, text triggers etc). I thought about writing my own editor but that's a bit luxurious at the moment, I'm still setting the core things up.
      Any ideas/help is greatly appreciated
      Thanks
      -vexe
    • By laiyierjiangsu
      Hi, guys!
                   My prograss crashs with a stackoverflow exception in some pcs.  I changed the stacksize of thread from default(1M) to (2M) for fixing this problem. But  I have got confused with some doubts.
      1、Why this exception happens in some pcs not all?  I think the logic is the same ,so the stack used must be identified too.
      2、Why the default stack size is 1M? Just for saving the memory of process or have some other reasons?
      3、Can there any tools or methods for me to find the logic where using so much stack?
    • By terrysworkstations
      I got some code that im tweaking. Ive almost got it to work. It doesn't seem to work right though. First when it first starts in my INIT function that I set to target 50,0,0, it jets off way to fast. Here is what im doing.
       
      seek(IvVector3 target) { IvVector3 desired = target - position; desired.Normalize(); desired = desired * maxspeed; IvVector3 steer = desired - velocity; if(steer.LengthSquared() > maxforce * maxforce) { steer.Normalize(); steer *= maxforce; } applyForce(steer); } void applyForce(IvVector3 Force) { acceleration = Force; } In my update Function
       
      velocity += acceleration; if(GetKeyState(0x31)) { seek(IvVector3(0,0,50)); } if(GetKeyState(0x32)) { seek(IvVector3(-50,0,0)); } position += (velocity * mTimer.DeltaTime()); TESTS = XMMatrixTranslation(position.x,0,position.z); // Reset acceleration to 0 each cycle acceleration.IsZero(); Also when it reaches the target, it completey stops instead of going back and forth