473,671 Members | 2,221 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

need help w/ multi-threaded, multi-CPU tick count / stopwatch

So I have a motherboard with multiple CPU sockets. It seems that if I
create a StopWatch on one thread and then call the Elapsed member from
a different thread that sometimes I get a tick count that's a million
miles away.

My thinking is that I can subclass the StopWatch. Then when the
Elapsed member is called, I can invoke it on the thread that the
StopWatch class was created on. True? How?

Or is there an easy way that I could scan through all processors and
read their tick counts? That way I could just have my own timer class
that stores counts for all CPUs.

Can the BeginThreadAffi nity help me somehow? I'm totally at a loss as
to what that function does for me.

Is there some other solution?

I'm using .NET 2.0.

Thanks.

Feb 14 '07 #1
5 10841
On Feb 14, 1:44 pm, "not_a_comm ie" <notacom...@gma il.comwrote:
So I have a motherboard with multiple CPU sockets. It seems that if I
create a StopWatch on one thread and then call the Elapsed member from
a different thread that sometimes I get a tick count that's a million
miles away.

My thinking is that I can subclass the StopWatch. Then when the
Elapsed member is called, I can invoke it on the thread that the
StopWatch class was created on. True? How?

Or is there an easy way that I could scan through all processors and
read their tick counts? That way I could just have my own timer class
that stores counts for all CPUs.

Can the BeginThreadAffi nity help me somehow? I'm totally at a loss as
to what that function does for me.

Is there some other solution?

I'm using .NET 2.0.

Thanks.
Hi,

The StopWatch class isn't inherently thread-safe. Are you
synchronizing access to it appropriately. Can you post some code
demonstrating the problem?

Brian

Feb 14 '07 #2
"not_a_comm ie" <no********@gma il.comwrote in message
news:11******** **************@ m58g2000cwm.goo glegroups.com.. .
So I have a motherboard with multiple CPU sockets. It seems that if I
create a StopWatch on one thread and then call the Elapsed member from
a different thread that sometimes I get a tick count that's a million
miles away.

My thinking is that I can subclass the StopWatch. Then when the
Elapsed member is called, I can invoke it on the thread that the
StopWatch class was created on. True? How?

Or is there an easy way that I could scan through all processors and
read their tick counts? That way I could just have my own timer class
that stores counts for all CPUs.

Can the BeginThreadAffi nity help me somehow? I'm totally at a loss as
to what that function does for me.

Is there some other solution?

I'm using .NET 2.0.

Thanks.
Check this: http://support.microsoft.com/?id=896256

Willy.

Feb 14 '07 #3
The StopWatch class isn't inherently thread-safe. Are you
synchronizing access to it appropriately. Can you post some code
demonstrating the problem?
Right. The StopWatch class expects that the Reset/Start/Stop/Elapsed*
methods are all accessed from the same thread. Not only that, they all
have to be accessed from the same CPU. Does StopWatch use the
BeginThreadAffi nity internally to make this happen? I'll assume that
it does. The problem is that if you need to call Reset in one thread
and Elapsed in another, this is very difficult. I did manage to make a
class to do it, however. Here it is for your critique:

using System;
using System.Runtime. InteropServices ;
using System.Diagnost ics;
using System.Threadin g;

namespace Blah
{
/// <summary>
/// Represents a high-resolution stopwatch that is thread-safe and
CPU safe.
/// </summary>
public sealed class StopWatch
{
static private Thread _backgroundThre ad = null;
static private EventWaitHandle _tickCountUpdat eRequest = new
EventWaitHandle (false, EventResetMode. AutoReset);
static private EventWaitHandle _tickCountUpdat eDone = new
EventWaitHandle (false, EventResetMode. AutoReset);

static public long Frequency = 0;
static public long CurrentTickCoun t = 0;

public long StartTickCount = 0;

/// <summary>
/// A thread to make sure CPU tick counts are always read from the
same CPU
/// </summary>
private static void _backgroundThre adFunc()
{
Thread.BeginThr eadAffinity();
Frequency = System.Diagnost ics.Stopwatch.F requency;
while (true)
{
_tickCountUpdat eRequest.WaitOn e();
CurrentTickCoun t = System.Diagnost ics.Stopwatch.G etTimestamp();
_tickCountUpdat eDone.Set();
}
//Thread.EndThrea dAffinity(); // never called
}

/// <summary>
/// The System.Diagnost ics.Stopwatch (and hence, performance
counters) get their tick marks from the CPU that the thread is on. We
create a thread to make sure the tick counts are always read on the
same CPU.
/// </summary>
static StopWatch() {
_backgroundThre ad = new Thread(new
ThreadStart(_ba ckgroundThreadF unc));
_backgroundThre ad.IsBackground = true;
_backgroundThre ad.Start();
}

/// <summary>
/// Initializes a new instance of the StopWatch class.
/// </summary>
/// <exception cref="NotSuppor tedException">T he system does not have
a high-resolution performance counter.</exception>
public StopWatch()
{
Reset();
}

/// <summary>
/// Resets the stopwatch. This method should be called when you
start measuring.
/// </summary>
/// <exception cref="NotSuppor tedException">T he system does not have
a high-resolution performance counter.</exception>
public void Reset()
{
lock (_backgroundThr ead)
{
StopWatch._tick CountUpdateRequ est.Set();
StopWatch._tick CountUpdateDone .WaitOne();
StartTickCount = CurrentTickCoun t;
}
}

/// <summary>
/// Peg the processor for this many seconds; mainly used for testing
/// </summary>
/// <param name="seconds"> </param>
public static void BusyLoop(double seconds)
{
DateTime endTime = DateTime.Now.Ad dSeconds(second s);
int i = 0;
while (DateTime.Now < endTime) { i++; }
}

public long GetCurrentTime_ ms()
{
lock (_backgroundThr ead)
{
StopWatch._tick CountUpdateRequ est.Set();
StopWatch._tick CountUpdateDone .WaitOne();
return CurrentTickCoun t * 1000 / StopWatch.Frequ ency;
}
}

/// <summary>
/// Get the time elapsed, in seconds, since the last Reset() or
since
/// creation if Reset() hasn't been called since then.
/// </summary>
/// <returns>Elapse d time in seconds.</returns>
public double GetElapsed_s()
{
lock (_backgroundThr ead)
{
StopWatch._tick CountUpdateRequ est.Set();
StopWatch._tick CountUpdateDone .WaitOne();
return (double)(Curren tTickCount - StartTickCount) /
(double)StopWat ch.Frequency;
}
}

/// <summary>
/// Get the time elapsed, in milliseconds, since the last Reset() or
since
/// creation if Reset() hasn't been called since then.
/// </summary>
/// <returns>Elapse d time in milliseconds.</returns>
public long GetElapsed_ms()
{
lock (_backgroundThr ead)
{
StopWatch._tick CountUpdateRequ est.Set();
StopWatch._tick CountUpdateDone .WaitOne();
return (CurrentTickCou nt - StartTickCount) * 1000 /
StopWatch.Frequ ency;
}
}
}
}

Feb 14 '07 #4
"not_a_comm ie" <no********@gma il.comwrote in message
news:11******** *************@l 53g2000cwa.goog legroups.com...
>The StopWatch class isn't inherently thread-safe. Are you
synchronizin g access to it appropriately. Can you post some code
demonstratin g the problem?

Right. The StopWatch class expects that the Reset/Start/Stop/Elapsed*
methods are all accessed from the same thread. Not only that, they all
have to be accessed from the same CPU. Does StopWatch use the
BeginThreadAffi nity internally to make this happen? I'll assume that
it does. The problem is that if you need to call Reset in one thread
and Elapsed in another, this is very difficult. I did manage to make a
class to do it, however. Here it is for your critique:

using System;
using System.Runtime. InteropServices ;
using System.Diagnost ics;
using System.Threadin g;

namespace Blah
{
/// <summary>
/// Represents a high-resolution stopwatch that is thread-safe and
CPU safe.
/// </summary>
public sealed class StopWatch
{
static private Thread _backgroundThre ad = null;
static private EventWaitHandle _tickCountUpdat eRequest = new
EventWaitHandle (false, EventResetMode. AutoReset);
static private EventWaitHandle _tickCountUpdat eDone = new
EventWaitHandle (false, EventResetMode. AutoReset);

static public long Frequency = 0;
static public long CurrentTickCoun t = 0;

public long StartTickCount = 0;

/// <summary>
/// A thread to make sure CPU tick counts are always read from the
same CPU
/// </summary>
private static void _backgroundThre adFunc()
{
Thread.BeginThr eadAffinity();
Frequency = System.Diagnost ics.Stopwatch.F requency;
while (true)
{
_tickCountUpdat eRequest.WaitOn e();
CurrentTickCoun t = System.Diagnost ics.Stopwatch.G etTimestamp();
_tickCountUpdat eDone.Set();
}
//Thread.EndThrea dAffinity(); // never called
}

/// <summary>
/// The System.Diagnost ics.Stopwatch (and hence, performance
counters) get their tick marks from the CPU that the thread is on. We
create a thread to make sure the tick counts are always read on the
same CPU.
/// </summary>
static StopWatch() {
_backgroundThre ad = new Thread(new
ThreadStart(_ba ckgroundThreadF unc));
_backgroundThre ad.IsBackground = true;
_backgroundThre ad.Start();
}

/// <summary>
/// Initializes a new instance of the StopWatch class.
/// </summary>
/// <exception cref="NotSuppor tedException">T he system does not have
a high-resolution performance counter.</exception>
public StopWatch()
{
Reset();
}

/// <summary>
/// Resets the stopwatch. This method should be called when you
start measuring.
/// </summary>
/// <exception cref="NotSuppor tedException">T he system does not have
a high-resolution performance counter.</exception>
public void Reset()
{
lock (_backgroundThr ead)
{
StopWatch._tick CountUpdateRequ est.Set();
StopWatch._tick CountUpdateDone .WaitOne();
StartTickCount = CurrentTickCoun t;
}
}

/// <summary>
/// Peg the processor for this many seconds; mainly used for testing
/// </summary>
/// <param name="seconds"> </param>
public static void BusyLoop(double seconds)
{
DateTime endTime = DateTime.Now.Ad dSeconds(second s);
int i = 0;
while (DateTime.Now < endTime) { i++; }
}

public long GetCurrentTime_ ms()
{
lock (_backgroundThr ead)
{
StopWatch._tick CountUpdateRequ est.Set();
StopWatch._tick CountUpdateDone .WaitOne();
return CurrentTickCoun t * 1000 / StopWatch.Frequ ency;
}
}

/// <summary>
/// Get the time elapsed, in seconds, since the last Reset() or
since
/// creation if Reset() hasn't been called since then.
/// </summary>
/// <returns>Elapse d time in seconds.</returns>
public double GetElapsed_s()
{
lock (_backgroundThr ead)
{
StopWatch._tick CountUpdateRequ est.Set();
StopWatch._tick CountUpdateDone .WaitOne();
return (double)(Curren tTickCount - StartTickCount) /
(double)StopWat ch.Frequency;
}
}

/// <summary>
/// Get the time elapsed, in milliseconds, since the last Reset() or
since
/// creation if Reset() hasn't been called since then.
/// </summary>
/// <returns>Elapse d time in milliseconds.</returns>
public long GetElapsed_ms()
{
lock (_backgroundThr ead)
{
StopWatch._tick CountUpdateRequ est.Set();
StopWatch._tick CountUpdateDone .WaitOne();
return (CurrentTickCou nt - StartTickCount) * 1000 /
StopWatch.Frequ ency;
}
}
}
}

Please read my other reply, your issue is probably related to a failure of the SMP HAL to
synchronize the CPU clocks when running this on anything else than Vista or Longorn.

Willy.

Feb 14 '07 #5
On Feb 14, 3:34 pm, "not_a_comm ie" <notacom...@gma il.comwrote:
Right. The StopWatch class expects that the Reset/Start/Stop/Elapsed*
methods are all accessed from the same thread. Not only that, they all
have to be accessed from the same CPU. Does StopWatch use the
BeginThreadAffi nity internally to make this happen? I'll assume that
it does. The problem is that if you need to call Reset in one thread
and Elapsed in another, this is very difficult. I did manage to make a
class to do it, however. Here it is for your critique:
Ah yes, there are processor affinity problems. I didn't notice this
note the first time I read through the documentation.

"On a multiprocessor computer, it does not matter which processor the
thread runs on. However, because of bugs in the BIOS or the Hardware
Abstraction Layer (HAL), you can get different timing results on
different processors. To specify processor affinity for a thread, use
the ProcessThread.P rocessorAffinit y method."

I didn't see anything about thread affinity though so it should work
when called from different threads right?

Brian

Feb 14 '07 #6

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

Similar topics

0
2438
by: Sofia | last post by:
My name is Sofia and I have for many years been running a personals site, together with my partner, on a non-profit basis. The site is currently not running due to us emigrating, but during its last year we got traffic of between 2000 - 2500 unique visitors per day. We are now about to re-launch the site from Sweden and we need to purchase a script to run it. Having looked at what is available on the net I have realised that we need a...
6
2172
by: Robert Maas, see http://tinyurl.com/uh3t | last post by:
System login message says PHP is available, so I tried this: http://www.rawbw.com/~rem/HelloPlus/h.php It doesn't work at all. Browser just shows the source. What am I doing wrong?
0
2427
by: Gregory Nans | last post by:
hello, i need some help to 'tree-ify' a string... for example i have strings such as : s = """A(here 's , B(A ) silly test) C(to show D(what kind) of stuff i need))""" and i need to parse them to have a tree representation such as :
7
4384
by: Mike Kamermans | last post by:
I hope someone can help me, because what I'm going through at the moment trying to edit XML documents is enough to make me want to never edit XML again. I'm looking for an XML editor that has a few features that you'd expect in any editor, except nearly none of them seem to have: 1 - Search and repalce with Regular Expressions. 2 - Search and Replace in an Xpath context. 3 - User specified tag-generation for either on a...
8
2834
by: JustSomeGuy | last post by:
I need to write an new class derived from the list class. This class stores data in the list to the disk if an object that is added to the list is over 1K in size. What methods of the std stl list class must Ioverride in order for this to work?
3
2624
by: Bob.Henkel | last post by:
I write this to tell you why we won't use postgresql even though we wish we could at a large company. Don't get me wrong I love postgresql in many ways and for many reasons , but fact is fact. If you need more detail I can be glad to prove all my points. Our goal is to make logical systems. We don't want php,perl, or c++ making all the procedure calls and having the host language to be checking for errors and handleing all the...
2
1946
by: Michael R. Pierotti | last post by:
Dim reg As New Regex("^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$") Dim m As Match = reg.Match(txtIPAddress.Text) If m.Success Then 'No need to do anything here Else MessageBox.Show("You need to enter a valid IP Address", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Hand) txtIPAddress.Focus() Return End If
10
2578
by: L. R. Du Broff | last post by:
I own a small business. Need to track a few hundred pieces of rental equipment that can be in any of a few dozen locations. I'm an old-time C language programmer (UNIX environment). If the only tool you know how to use is a hammer, every problem tends to look like a nail. That said, I could solve my problem in C, but it's not the right tool. I need to come into the Windows world, and I need to get this done in Access or something...
23
2532
by: vinod.bhavnani | last post by:
Hello all, I need desperate help Here is the problem: My problem today is with multidimensional arrays. Lets say i have an array A this is a 4 dimensional static array.
0
3946
by: U S Contractors Offering Service A Non-profit | last post by:
Brilliant technology helping those most in need Inbox Reply U S Contractors Offering Service A Non-profit show details 10:37 pm (1 hour ago) Brilliant technology helping those most in need Inbox Reply from Craig Somerford <uscos@2barter.net> hide details 10:25 pm (3 minutes ago)
0
8393
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,...
0
8917
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8821
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8598
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
8670
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7437
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...
0
5696
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();...
1
2812
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
2051
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.