473,383 Members | 1,922 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

High resolution Sleep

Sleep() function Sleep at lease 1 millisecond, there is a way to make a
thread to sleep less than a millisecond? One way I know of is using
performance counter which is not really sleep ( loop and check again and
again and uses CPU time).

Thanks

Charles Zhang
Apr 2 '08 #1
13 5770
Even Sleep() doesn't have true 1 ms resolution.

There's no better timer than the performance counter in Windows AFAIK.

Mark

--
Mark Salsbery
Microsoft MVP - Visual C++
"Charles Zhang" <Ch**********@newsgroups.nospamwrote in message
news:Ov**************@TK2MSFTNGP02.phx.gbl...
Sleep() function Sleep at lease 1 millisecond, there is a way to make a
thread to sleep less than a millisecond? One way I know of is using
performance counter which is not really sleep ( loop and check again and
again and uses CPU time).

Thanks

Charles Zhang
Apr 2 '08 #2
and.. what about with time struct?

hh:mm:ss,dd

where 99>=dd>=0

dd are miliseconds...

and thinking a little more, what about cpu cicles?


"Mark Salsbery [MVP]" <MarkSalsbery[MVP]@newsgroup.nospamescribió en el
mensaje news:75**********************************@microsof t.com...
Even Sleep() doesn't have true 1 ms resolution.

There's no better timer than the performance counter in Windows AFAIK.

Mark

--
Mark Salsbery
Microsoft MVP - Visual C++
"Charles Zhang" <Ch**********@newsgroups.nospamwrote in message
news:Ov**************@TK2MSFTNGP02.phx.gbl...
>Sleep() function Sleep at lease 1 millisecond, there is a way to make a
thread to sleep less than a millisecond? One way I know of is using
performance counter which is not really sleep ( loop and check again and
again and uses CPU time).

Thanks

Charles Zhang

Apr 2 '08 #3
You can use "clockres" from Sysinternals (today Microsoft) to see the
minimum resolution in your machine. Mine (Quad core is 15.6 ms).

I think less than 15 ms is impossible, and surely a sleep of 15 ms becomes
in a lot of more time because Windows uses that sleeping to do other tasks,
and if you put a for() loop you will get your CPU time scalated to 100% and
surely with no more precission that sleep.

"Charles Zhang" <Ch**********@newsgroups.nospamwrote in message
news:Ov**************@TK2MSFTNGP02.phx.gbl...
Sleep() function Sleep at lease 1 millisecond, there is a way to make a
thread to sleep less than a millisecond? One way I know of is using
performance counter which is not really sleep ( loop and check again and
again and uses CPU time).

Thanks

Charles Zhang
--
Microsoft Visual C++ MVP
========================
Mi blog sobre programación: http://geeks.ms/blogs/rfog
Momentos Leves: http://momentosleves.blogspot.com/
Libros, ciencia ficción y programación
========================================
Es un hecho que el hombre tiene que controlar la ciencia y chequear
ocasionalmente el avance de la tecnología.
-- Thomas Henry Huxley.

Apr 2 '08 #4
Hi RFOG!
I think less than 15 ms is impossible, and surely a sleep of 15 ms
becomes in a lot of more time because Windows uses that sleeping to do
other tasks, and if you put a for() loop you will get your CPU time
scalated to 100% and surely with no more precission that sleep.
If you use "timeBeginPeriod(1)" you can mostly reduce the time-slice to
2 ms.

Greetings
Jochen
Apr 2 '08 #5
"Jochen Kalmbach [MVP]" <no********************@holzma.dewrote in message
news:%2******************@TK2MSFTNGP05.phx.gbl...
Hi RFOG!
>I think less than 15 ms is impossible, and surely a sleep of 15 ms
becomes in a lot of more time because Windows uses that sleeping to do
other tasks, and if you put a for() loop you will get your CPU time
scalated to 100% and surely with no more precission that sleep.

If you use "timeBeginPeriod(1)" you can mostly reduce the time-slice to 2
ms.

Greetings
Jochen

True, but this won't guarantee that your thread will get scheduled right
after 2ms. The scheduler is master of the game here, once you give up your
quantum, you'll have to wait until all other higher priority threads have
run.

Willy.

Apr 2 '08 #6
Hi Willy!
True, but this won't guarantee that your thread will get scheduled right
after 2ms. The scheduler is master of the game here,
Yes...
once you give up
your quantum, you'll have to wait until all other higher priority
threads have run.
No. If a higher prio thread becomes ready to run, your quantum does not
matter. Your thread will be immediately interrupted and the higher prio
thread will run.

Greetings
Jochen
Apr 2 '08 #7
Hi Willy!
No.
I wanted to say: This is only some side of the truth... sorry...

Greetings
Jochen
Apr 2 '08 #8
Charles Zhang wrote:
Sleep() function Sleep at lease 1 millisecond, there is a way to make
a thread to sleep less than a millisecond? One way I know of is using
performance counter which is not really sleep ( loop and check again
and again and uses CPU time).
Waitable Timers allow the wait to be specified very precisely, however the
actual resolution will depend on the system clock interrupt.
timeBeginPeriod can make the clock interrupt faster to a point, I don't know
of any user-mode way to set the interrupt rate above 1kHz.
>
Thanks

Charles Zhang

Apr 2 '08 #9
"Ben Voigt [C++ MVP]" <rb*@nospam.nospamwrote in message
news:Ok**************@TK2MSFTNGP05.phx.gbl...
Willy Denoyette [MVP] wrote:
>"Jochen Kalmbach [MVP]" <no********************@holzma.dewrote in
message news:OF*************@TK2MSFTNGP06.phx.gbl...
>>Hi Willy!

True, but this won't guarantee that your thread will get scheduled
right after 2ms. The scheduler is master of the game here,

Yes...

once you give up your quantum, you'll have to wait until all other
higher priority threads have run.

No. If a higher prio thread becomes ready to run, your quantum does
not matter. Your thread will be immediately interrupted and the
higher prio thread will run.

Hi Jochen,

I mean :
T1 normal priority calls sleep(2) - that is, give up your quantum now!
T2 normal priority gets scheduled runs for 1msec and enters a wait
state T3 higher priority gets scheduled and runs for 1 sec.
T1 as slept ~1 sec

This isn't a drawback to calling sleep though, any wait method could be
pre-empted by a higher priority thread.
True, and for the same reason you can't use them to "wait" for an "exact"
(especially small) amount of time when running on a Windows OS (even not on
Windows CE). Point is that once your (1) thread enters a wait state, you are
at the "mercy" of the scheduler to (2) wake you up. You are under control of
the first action, but you aren't of the second.
So whether you call Sleep(1) or WaitForSingleObject(..., 1), you will wait
for at *least* the RTC timer interval, whatever it's value.

Willy.

Apr 2 '08 #10

"Jordi Maycas" <jm***********@hotmail.comwrote in message
news:el**************@TK2MSFTNGP06.phx.gbl...
and.. what about with time struct?

hh:mm:ss,dd

where 99>=dd>=0

dd are miliseconds...

Yes, many APIs have 1ms units in parameters. Some use 100-nanosecond units.
But the actual accuracy is much less than 1ms.

See Charles Wang's response below...

>
and thinking a little more, what about cpu cicles?

Now you're at the performance counter level :)

Mark

--
Mark Salsbery
Microsoft MVP - Visual C++
>

"Mark Salsbery [MVP]" <MarkSalsbery[MVP]@newsgroup.nospamescribió en el
mensaje news:75**********************************@microsof t.com...
>Even Sleep() doesn't have true 1 ms resolution.

There's no better timer than the performance counter in Windows AFAIK.

Mark

--
Mark Salsbery
Microsoft MVP - Visual C++
"Charles Zhang" <Ch**********@newsgroups.nospamwrote in message
news:Ov**************@TK2MSFTNGP02.phx.gbl...
>>Sleep() function Sleep at lease 1 millisecond, there is a way to make a
thread to sleep less than a millisecond? One way I know of is using
performance counter which is not really sleep ( loop and check again and
again and uses CPU time).

Thanks

Charles Zhang

Apr 2 '08 #11
You can get Sleep() delay on XP close to the current timer resolution
but measuring the actual sleep time can be difficult.
I've made a simple test based on Sysinternals clockres sample.

The minimal resolution is 1 or 2 ms on most modern systems where the
default is 15.6 ms, and 1 ms on older systems where the default was 10 ms.
AFAIK there still is no good explanation why the newer PCs have default
resolution 10 ms.

Surprising is that value returned by GetSystemTimeAsFileTime or
NtQuerySystemTime
seems to update only once in system clock tick (15.6 ms in my case),
so when I call GetSystemTimeAsFileTime before and after Sleep(1), I got
_same_ value 7 times out of 8;
and on 8th time the difference jumps to 15 ms :( So the average Sleep()
delay of many samples is close to 1 ms.

Regards,
--PA
Apr 2 '08 #12
Pavel A. wrote:
You can get Sleep() delay on XP close to the current timer resolution
but measuring the actual sleep time can be difficult.
Not difficult, just use QueryPerformanceCounter.
I've made a simple test based on Sysinternals clockres sample.

The minimal resolution is 1 or 2 ms on most modern systems where the
default is 15.6 ms, and 1 ms on older systems where the default was
10 ms. AFAIK there still is no good explanation why the newer PCs
have default resolution 10 ms.

Surprising is that value returned by GetSystemTimeAsFileTime or
NtQuerySystemTime
seems to update only once in system clock tick (15.6 ms in my case),
so when I call GetSystemTimeAsFileTime before and after Sleep(1), I
got _same_ value 7 times out of 8;
and on 8th time the difference jumps to 15 ms :( So the average
Sleep() delay of many samples is close to 1 ms.

Regards,
--PA

Apr 2 '08 #13
"Pavel A." <pa*****@NOwritemeNO.comwrote in message
news:OP**************@TK2MSFTNGP03.phx.gbl...
You can get Sleep() delay on XP close to the current timer resolution
but measuring the actual sleep time can be difficult.
I've made a simple test based on Sysinternals clockres sample.

The minimal resolution is 1 or 2 ms on most modern systems where the
default is 15.6 ms, and 1 ms on older systems where the default was 10 ms.
AFAIK there still is no good explanation why the newer PCs have default
resolution 10 ms.

Surprising is that value returned by GetSystemTimeAsFileTime or
NtQuerySystemTime
seems to update only once in system clock tick (15.6 ms in my case),
so when I call GetSystemTimeAsFileTime before and after Sleep(1), I got
_same_ value 7 times out of 8;
and on 8th time the difference jumps to 15 ms :( So the average Sleep()
delay of many samples is close to 1 ms.

Regards,
--PA



Indeed, measuring is the key, but as I said before, you can't Sleep (or
Wait) for a reliable amount of time,
when sleeping (waiting) for < RTC interval, you give up your remaining
quantum, and you may possibly get re-scheduled after this period of time,
that is, after X msec. where X >= the remaining quantum.
For instance when you call Sleep(1) after your thread has run for Y msec,
you will probably sleep for 15.6 - X msec. on current multi-core/SMP
systems.
When you call Sleep(1) after your thread consumed 10 µsec of it's quantum,
this thread will sleep for at least 15.6 msec.
When you call Sleep(1) after your thread has consumed 14 msec you will sleep
for at least 1.6 msec.
That means you cannot reliably sleep with Windows ;-)

Compile and run the following sample , you'll see what I mean.
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <process.h>
#include <cstdio>
#include <math.h>
unsigned __stdcall Run(void* dummy)
{
double r = 0.0;
for(int i = 0; i < 50000000; i++)
{
r += (double)sqrt((double)i);
}
printf_s("%Lf\n", r);
_endthreadex(0);
return 0;
}
int main() {
__int64 startcount, stopCount, frequ;
QueryPerformanceFrequency((LARGE_INTEGER*)&frequ);
HANDLE tHandle;
unsigned thread_Id;
Sleep(1); // Give up the current quantum so we can start with a fresh one
after return
tHandle = reinterpret_cast<HANDLE>(_beginthreadex(0, 0, &Run, 0, 0,
&thread_Id ));
QueryPerformanceCounter((LARGE_INTEGER*)&startcoun t);
Sleep(1);
//Or, use next
// WaitForSingleObject(tHandle, 1); // wait for thread to finish or timeout
QueryPerformanceCounter((LARGE_INTEGER*)&stopCount );
CloseHandle(tHandle);
printf_s("%Lf seconds\n", (double)(stopCount - startcount)/frequ);
return 0;
}

Willy.

Apr 2 '08 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Ben Amada | last post by:
Hi group. I'm going to display a low resolution image in an HTML page. On the web server, I have a high resolution version of that image. If I display the high resolution image in the browser...
2
by: Michael Evans | last post by:
First, we rely on a stable update rate so that our physics and dynamics calculations and integrations are based on a known interval and therefore are true-to-life. Second, the graphics positions...
6
by: moondaddy | last post by:
I have an application where I need to print images where the size has been reduced down to a fraction of a thumbnail and the original image is several inches high and wide. We're using a special...
3
subashini Thiyagarajan
by: subashini Thiyagarajan | last post by:
Hi all, The animated flash documents are not having good resolution.can any one suggest how can i get high resolution picture in flash with good clarity.what i need to do for that. expecting some...
19
by: John | last post by:
The table below shows the execution time for this code snippet as measured by the unix command `time': for i in range(1000): time.sleep(inter) inter execution time ideal 0 ...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.