473,769 Members | 3,084 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

High res timer

Is it possible to have a synchronous thread... actually a timer that is
beyond the 1khz/1ms resolution that .NET offers?

I want to poll the parallel port at rates beyond 1khz... about 10 to 100
times that rate if possible.

Essnetially I want to monitor the parallel port for data and display it but
I need a fast but somewhat precise way of knowing the sample rate.

Doing some tests on just a simple thread I can get speeds at around 150mhz
or so with a normal priority System.Thread. I figure that since I just need
about 1/1000 of that it shouldn't be that big a deal.

Is this possible in C#.NET? If not, is it possible to write a simple driver
in unmanaged C++ that either polls the port or hooks onto an
interrupt(synce d) to get the data to a C# app?

Thanks,
Jon
Sep 6 '07
19 3447
"Jon Slaughter" <Jo***********@ Hotmail.comwrot e in message
news:Eo******** **********@news svr11.news.prod igy.net...
>
"Jon Slaughter" <Jo***********@ Hotmail.comwrot e in message
news:Pk******** **********@news svr11.news.prod igy.net...
>>
What I did was made an unmanaged C++ function that is a simple delay
using n nops. I figure I can profile some test code and get an average
speed and then use as a timer. I suppose it might work good enough.... or
atleast until I find a better method

Thanks,
Jon

Now I'm limited to about 100khz max. Just the act of inserting the a dll
call has made it 1000 times slower. I suppose this has something to do
with going from managed to unmanaged code. In any case I think it will be
ok for now.

Tag your function with [SuppressUnmanag edCodeSecurity] in the p/invoke
declaration if you haven't already done so...

whan I'm talking about a spin loop I mean something like (now, don't forget
the overhead of actually making the function calls and doing the math <g>):
(you can dllimport the functions to C# too, declare the function as
[DllImport("kern el32.dll"), SuppressUnmanag edCodeSecurity]
[return: MarshalAs(Unman agedType.Bool)]
bool QueryPerformanc eCounter(out long count);

double requiredTimeToW aitInSeconds = 0.00001; // ten microseconds
QueryPerformanc eFrequency(&fre q);
QueryPerformanc eCounter(&start );
do
{
QueryPerformanc eCounter(&end);
if (((end.QuadPart - start.QuadPart) / (double)freq.Qu adPart) >
requiredTimeToW aitInSeconds)
break;
Sleep(0); // Give up time slice
} while(true);

In fact, I'm wondering if you can't use the new StopWatch class which uses
QueryPerformanc eCounter internally): Something like:

Stopwatch s = Stopwatch.Start New();
while (s.ElapsedTicks / StopWatch.Frequ ency < requiredTimeToW aitInSeconds)
// Fastest way to get elapsed time is ElapsedTicks
Threading.Sleep (0);

--
Doug Semler, MCPD
a.a. #705, BAAWA. EAC Guardian of the Horn of the IPU (pbuhh).
The answer is 42; DNRC o-
Gur Hfrarg unf orpbzr fb shyy bs penc gurfr qnlf, abbar rira
erpbtavmrf fvzcyr guvatf yvxr ebg13 nalzber. Fnq, vfa'g vg?

Sep 7 '07 #11

"Doug Semler" <do********@gma il.comwrote in message
news:%2******** **********@TK2M SFTNGP02.phx.gb l...
"Jon Slaughter" <Jo***********@ Hotmail.comwrot e in message
news:Eo******** **********@news svr11.news.prod igy.net...
>>
"Jon Slaughter" <Jo***********@ Hotmail.comwrot e in message
news:Pk******* ***********@new ssvr11.news.pro digy.net...
>>>
What I did was made an unmanaged C++ function that is a simple delay
using n nops. I figure I can profile some test code and get an average
speed and then use as a timer. I suppose it might work good enough....
or atleast until I find a better method

Thanks,
Jon

Now I'm limited to about 100khz max. Just the act of inserting the a dll
call has made it 1000 times slower. I suppose this has something to do
with going from managed to unmanaged code. In any case I think it will be
ok for now.


Tag your function with [SuppressUnmanag edCodeSecurity] in the p/invoke
declaration if you haven't already done so...

whan I'm talking about a spin loop I mean something like (now, don't
forget the overhead of actually making the function calls and doing the
math <g>):
(you can dllimport the functions to C# too, declare the function as
[DllImport("kern el32.dll"), SuppressUnmanag edCodeSecurity]
[return: MarshalAs(Unman agedType.Bool)]
bool QueryPerformanc eCounter(out long count);

double requiredTimeToW aitInSeconds = 0.00001; // ten microseconds
QueryPerformanc eFrequency(&fre q);
QueryPerformanc eCounter(&start );
do
{
QueryPerformanc eCounter(&end);
if (((end.QuadPart - start.QuadPart) / (double)freq.Qu adPart) >
requiredTimeToW aitInSeconds)
break;
Sleep(0); // Give up time slice
} while(true);
Yes, this was essentially what I was doing... I didn't know it was called as
spinloop. I also found out that System.Threads has a Thread.SpinWait (n)
which, I suppose, does exactly what my delay does but seems to do it a
little more efficiently(I a better spread with it atleast).

If I understand correctly though then the SpinWait will not be interrupted
and not only burn cycles but prevent other threads from running? I guess
this won't be a problem except if I use it for very large times.

In reality I think any of these methods will work because I will not be
using the thread all that often; just to send commands back and form to the
device on the parallel port. In this case I can just sleep after a few
commands are send and so will only be spin looping for a fraction of a ms.

The main issue is if the thread gets interrupted in the middle of a command
by a process that takes very long.
In fact, I'm wondering if you can't use the new StopWatch class which uses
QueryPerformanc eCounter internally): Something like:

Stopwatch s = Stopwatch.Start New();
while (s.ElapsedTicks / StopWatch.Frequ ency < requiredTimeToW aitInSeconds)
// Fastest way to get elapsed time is ElapsedTicks
Threading.Sleep (0);
This seems like it cannot be any faster than calling PerformanceCoun ter
directly?

I'm going to go ahead and use Thread.SpinWait , unless I find some reasons
not too, and see what happens. I think everything will be ok.

Thanks,
Jon
Sep 7 '07 #12
On Sep 7, 12:52 am, "Jon Slaughter" <Jon_Slaugh...@ Hotmail.comwrot e:
"Doug Semler" <dougsem...@gma il.comwrote in message
>
In fact, I'm wondering if you can't use the new StopWatch class which uses
QueryPerformanc eCounter internally): Something like:
Stopwatch s = Stopwatch.Start New();
while (s.ElapsedTicks / StopWatch.Frequ ency < requiredTimeToW aitInSeconds)
// Fastest way to get elapsed time is ElapsedTicks
Threading.Sleep (0);

This seems like it cannot be any faster than calling PerformanceCoun ter
directly?
No. It's not. But it's cleaner to look at. The stopwatch loop is
(almost) functionally equivilent to the direct performance counter
loop I gave you
>
I'm going to go ahead and use Thread.SpinWait , unless I find some reasons
not too, and see what happens. I think everything will be ok.
Warning: SpinWait timings depend on the frequency of the processor...
(i believe spinwait does something very similar to:

for (int i = 1; i < n; i++)
nop

Sep 7 '07 #13
Jon,

this may also help to reach 1 ms resolution:

http://www.codeproject.com/csharp/hi...timercshar.asp

Best regards,
Janos

Sep 7 '07 #14
You might want to replace your "clicks++" with a Thread.SpinWait .

Joe Duffy has a number of articles on this that all show up in Google.

--
Chris Mullins, MCSD.NET, MCPD:Enterprise , Microsoft C# MVP
http://www.coversant.com/blogs/cmullins

"Jon Slaughter" <Jo***********@ Hotmail.comwrot e in message
news:VF******** ********@newssv r19.news.prodig y.net...
Well guys, this is what I've done
static void counter()

{

long startCount = PerfCount.Query PerformanceCoun ter();

double elapsedSeconds = 0;

double QPF = (double)PerfCou nt.QueryPerform anceFrequency() ;

while (true)

{

clicks++;

// Delay x seconds

/*

startCount = PerfCount.Query PerformanceCoun ter();

do

{

Delayer(1);

elapsedSeconds = (PerfCount.Quer yPerformanceCou nter() - startCount)/QPF;

} while (elapsedSeconds < 0.0000001);

*/

Delayer(100000) ;

}

}

}

I have another thread that gathers how many clicks past

Starting Thread Profiling...
18436 clicks, 9.205 khz
36567 clicks, 9.129 khz
54224 clicks, 9.024 khz
71853 clicks, 8.969 khz
89471 clicks, 8.934 khz
106669 clicks, 8.876 khz
124794 clicks, 8.901 khz
142910 clicks, 8.919 khz
161026 clicks, 8.933 khz
179568 clicks, 8.943 khz
Total Time: 20.0789 secs, Average Freq: 8.983 khz, Std Dev: 0.1 khz
Standard Jitter: 1.119%
Press any key to continue . . .

using a Delayer(0) (1 nop) gives

Starting Thread Profiling...
20622424 clicks, 10.297 mhz
40389803 clicks, 10.083 mhz
57608071 clicks, 9.588 mhz
75853991 clicks, 9.468 mhz
95928456 clicks, 9.579 mhz
116091324 clicks, 9.66 mhz
136231241 clicks, 9.717 mhz
156395445 clicks, 9.761 mhz
176444567 clicks, 9.788 mhz
196572318 clicks, 9.81 mhz
Total Time: 20.0388 secs, Average Freq: 9.775 mhz, Std Dev: 0.235 mhz
Standard Jitter: 2.405%
Press any key to continue . . .
I can control the freq from 0 to around 10mhz on my machine with usually
about 1-2% standard jitter. It always executes faster at the start for
some reason(I guess the GC starts to get in the way or something else?).

In any case, it does seem to give me the ability to control the
transmission rate even though I'm wasting a lot of cycles I think it will
work for now. Of course it doesn't help that much with monitoring the port
but maybe I can work something out.

Thanks,

Jon


Sep 7 '07 #15
Lit

Just wondering does the counters acts as a Timer Interrupt ( old assembly )?

Lit
"Jon Slaughter" <Jo***********@ Hotmail.comwrot e in message
news:AN******** ********@nlpi06 8.nbdc.sbc.com. ..
>
"Doug Semler" <do********@gma il.comwrote in message
news:%2******** **********@TK2M SFTNGP02.phx.gb l...
>"Jon Slaughter" <Jo***********@ Hotmail.comwrot e in message
news:Eo******* ***********@new ssvr11.news.pro digy.net...
>>>
"Jon Slaughter" <Jo***********@ Hotmail.comwrot e in message
news:Pk****** ************@ne wssvr11.news.pr odigy.net...

What I did was made an unmanaged C++ function that is a simple delay
using n nops. I figure I can profile some test code and get an average
speed and then use as a timer. I suppose it might work good enough....
or atleast until I find a better method

Thanks,
Jon

Now I'm limited to about 100khz max. Just the act of inserting the a dll
call has made it 1000 times slower. I suppose this has something to do
with going from managed to unmanaged code. In any case I think it will
be ok for now.


Tag your function with [SuppressUnmanag edCodeSecurity] in the p/invoke
declaration if you haven't already done so...

whan I'm talking about a spin loop I mean something like (now, don't
forget the overhead of actually making the function calls and doing the
math <g>):
(you can dllimport the functions to C# too, declare the function as
[DllImport("kern el32.dll"), SuppressUnmanag edCodeSecurity]
[return: MarshalAs(Unman agedType.Bool)]
bool QueryPerformanc eCounter(out long count);

double requiredTimeToW aitInSeconds = 0.00001; // ten microseconds
QueryPerforman ceFrequency(&fr eq);
QueryPerforman ceCounter(&star t);
do
{
QueryPerformanc eCounter(&end);
if (((end.QuadPart - start.QuadPart) / (double)freq.Qu adPart) >
requiredTimeTo WaitInSeconds)
break;
Sleep(0); // Give up time slice
} while(true);

Yes, this was essentially what I was doing... I didn't know it was called
as spinloop. I also found out that System.Threads has a Thread.SpinWait (n)
which, I suppose, does exactly what my delay does but seems to do it a
little more efficiently(I a better spread with it atleast).

If I understand correctly though then the SpinWait will not be interrupted
and not only burn cycles but prevent other threads from running? I guess
this won't be a problem except if I use it for very large times.

In reality I think any of these methods will work because I will not be
using the thread all that often; just to send commands back and form to
the device on the parallel port. In this case I can just sleep after a
few commands are send and so will only be spin looping for a fraction of a
ms.

The main issue is if the thread gets interrupted in the middle of a
command by a process that takes very long.
>In fact, I'm wondering if you can't use the new StopWatch class which
uses QueryPerformanc eCounter internally): Something like:

Stopwatch s = Stopwatch.Start New();
while (s.ElapsedTicks / StopWatch.Frequ ency <
requiredTimeTo WaitInSeconds) // Fastest way to get elapsed time is
ElapsedTicks
Threading.Sleep (0);

This seems like it cannot be any faster than calling PerformanceCoun ter
directly?

I'm going to go ahead and use Thread.SpinWait , unless I find some reasons
not too, and see what happens. I think everything will be ok.

Thanks,
Jon

Sep 7 '07 #16

"Doug Semler" <do********@gma il.comwrote in message
news:11******** **************@ 50g2000hsm.goog legroups.com...
On Sep 7, 12:52 am, "Jon Slaughter" <Jon_Slaugh...@ Hotmail.comwrot e:
>"Doug Semler" <dougsem...@gma il.comwrote in message
>>
In fact, I'm wondering if you can't use the new StopWatch class which
uses
QueryPerformanc eCounter internally): Something like:
Stopwatch s = Stopwatch.Start New();
while (s.ElapsedTicks / StopWatch.Frequ ency <
requiredTimeToW aitInSeconds)
// Fastest way to get elapsed time is ElapsedTicks
Threading.Sleep (0);

This seems like it cannot be any faster than calling PerformanceCoun ter
directly?

No. It's not. But it's cleaner to look at. The stopwatch loop is
(almost) functionally equivilent to the direct performance counter
loop I gave you
>>
I'm going to go ahead and use Thread.SpinWait , unless I find some reasons
not too, and see what happens. I think everything will be ok.

Warning: SpinWait timings depend on the frequency of the processor...
(i believe spinwait does something very similar to:

for (int i = 1; i < n; i++)
nop
Well, thats what my delayer is... I'm computing the freqencies and I'll
either use that to base how much to delay or use some adapative algorithm(if
it works well).

Thanks,
Jon
Sep 9 '07 #17

"Chris Mullins [MVP]" <cm******@yahoo .comwrote in message
news:e2******** ******@TK2MSFTN GP02.phx.gbl...
You might want to replace your "clicks++" with a Thread.SpinWait .

Joe Duffy has a number of articles on this that all show up in Google.
clicks++ is there to count how fast the thread is operating. The delayer or
SpinWait is there to control the frequency at which the clicks happen. So
both are needed... See my latest thread for issues with SpinWait(I like it
but causing a problem stopping the thread).

Thanks,
Jon
Sep 9 '07 #18

"Lit" <sq**********@h otmail.comwrote in message
news:eA******** *****@TK2MSFTNG P06.phx.gbl...
>
Just wondering does the counters acts as a Timer Interrupt ( old
assembly )?

Lit

I'm not sure what you mean but essentially the counter function is suppose
to act sorta like a timer that has better than millisecond accuracy.

Essentially what I do is time how fast the thread is able to count. So if it
counts N in 3 seconds then obviously N/3 is the frequency at which the
thread is running and 3/N is how fast it was able to count up to that point.

The delayer part is to slow down the counter to get an adjustable frequency.

The issues are obviously that you are wasting cpu and that the counter isn't
very stable in some cases. But for my app its not all that serious because
I'll only be using the thread for very short periods of time.

Jon
Sep 9 '07 #19
In fact, I'm wondering if you can't use the new StopWatch class which uses
QueryPerformanc eCounter internally): Something like:

Stopwatch s = Stopwatch.Start New();
while (s.ElapsedTicks / StopWatch.Frequ ency < requiredTimeToW aitInSeconds)
better:

long ticksToWait = StopWatch.Frequ ency * requiredTimeToW aitInSeconds;
while (s.ElapsedTicks < ticksToWait)

Never divide when you can multiply :)
// Fastest way to get elapsed time is ElapsedTicks
Threading.Sleep (0);

--
Doug Semler, MCPD
a.a. #705, BAAWA. EAC Guardian of the Horn of the IPU (pbuhh).
The answer is 42; DNRC o-
Gur Hfrarg unf orpbzr fb shyy bs penc gurfr qnlf, abbar rira
erpbtavmrf fvzcyr guvatf yvxr ebg13 nalzber. Fnq, vfa'g vg?

Sep 10 '07 #20

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

Similar topics

2
1652
by: Arsen V. | last post by:
Hello, Did anyone have some experience with the following: 1) Need to track high volume of impressions - 20,000,000+ per day 2) Backend is SQL Server 2000 3) Webfarm of IIS with ASP.NET 4) Need to track the data as follows: DATE, TIME (resolution should be 1 hour), ID, NUMBER OF IMPRESSIONS, SOME OTHER COUNTS
2
733
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 in our image generators are updated by this dynamics application, and we need to update them at the rate they are being refreshed so that we don't get any stutter from frames being used twice or having to be thrown out. Without microsecond...
7
4986
by: LBT | last post by:
I have a window service written using VB.NET. This window service will scan folders for file and grab the file content to be inserted to SQL Server on file detection. There are altogether 18 folders to be watched. Each folder is assigned with a timer for watching purpose. Hence there will be 18 timers and each timer is set to elapse on every second. Problem here, once the window service is installed and started, the CPU usage is very...
8
1567
by: bob | last post by:
I am unsure how to approach a C# windows App. Essentially I want to do this. I want to write an app that reads from database_A performs some calculations updates the pretty dials on the screen then writes the 'cooked' data to database_B (probably not in that order). Also I will have some buttons on this main window that open some other winforms so I can capture other bits of info and adjust the main window's pretty dials and textboxes...
0
1756
by: bg_ie | last post by:
Hi all, I'm writing a .net Com object to read messages from an external bus. Also, under certain situations, I output messages to the bus in order to generate bus load, for testing purposes. An idea of my code is supplied below, and as you can see I use Stopwatch to generate an accurate timer. DoLoop is my timer callback and it is called with an interval of 20ms. When doing the bus load I need the timer to perform as well as possible,...
19
15004
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 0.02 s 0 s 1e-4 4.29 s 0.1 s 1e-3 4.02 s 1 s
7
502
by: Andrew Wan | last post by:
I found this excellent High Speed Timer (in Pascal). I compiled it (using Turbo Pascal 7 and it runs fine): http://www.sorucevap.com/bilisimteknolojisi/programcilik/pascal/ders.asp?207995 and same High Speed Timer here too: http://groups.google.com/group/comp.lang.pascal/browse_thread/thread/92e9398f16c10ba4/e67ff3cf587648ef?lnk=st&q=inline(%24CD)+inline(%241C)+inline(%249C)&rnum=1&hl=en#e67ff3cf587648ef I converted it to C (using p2c),...
17
7968
by: Cesar | last post by:
Hello people. I'm having a Winform app that contains a webbrowser control that keeps navigating from one page to another permanentrly to make some tests. The problem I'm having is that after a while, the application is using more than 100 or 150 Mb in RAM, and if I let it continue, it can leave the system without memory. I've been watching in some pages that other people has the same problem with this control when keep navigating for a...
8
12684
alexis4
by: alexis4 | last post by:
Hello! I need to slide a picture from right to left. So I need a timer event. When this event comes, I decrease picturebox’s X position by 1. The thing is that I need a timer faster than 1ms. After some searching, I came up with the following demo code (timer is set for 1ms): using System; using System.Drawing; using System.Windows.Forms; using System.Windows.Threading; //WindowsBase.dll
0
9579
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9422
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9987
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8867
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7404
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6662
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5294
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3952
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3558
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.