473,396 Members | 2,020 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,396 software developers and data experts.

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 BeginThreadAffinity 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 10822
On Feb 14, 1:44 pm, "not_a_commie" <notacom...@gmail.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 BeginThreadAffinity 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_commie" <no********@gmail.comwrote in message
news:11**********************@m58g2000cwm.googlegr oups.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 BeginThreadAffinity 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
BeginThreadAffinity 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.Diagnostics;
using System.Threading;

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

static public long Frequency = 0;
static public long CurrentTickCount = 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 _backgroundThreadFunc()
{
Thread.BeginThreadAffinity();
Frequency = System.Diagnostics.Stopwatch.Frequency;
while (true)
{
_tickCountUpdateRequest.WaitOne();
CurrentTickCount = System.Diagnostics.Stopwatch.GetTimestamp();
_tickCountUpdateDone.Set();
}
//Thread.EndThreadAffinity(); // never called
}

/// <summary>
/// The System.Diagnostics.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() {
_backgroundThread = new Thread(new
ThreadStart(_backgroundThreadFunc));
_backgroundThread.IsBackground = true;
_backgroundThread.Start();
}

/// <summary>
/// Initializes a new instance of the StopWatch class.
/// </summary>
/// <exception cref="NotSupportedException">The 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="NotSupportedException">The system does not have
a high-resolution performance counter.</exception>
public void Reset()
{
lock (_backgroundThread)
{
StopWatch._tickCountUpdateRequest.Set();
StopWatch._tickCountUpdateDone.WaitOne();
StartTickCount = CurrentTickCount;
}
}

/// <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.AddSeconds(seconds);
int i = 0;
while (DateTime.Now < endTime) { i++; }
}

public long GetCurrentTime_ms()
{
lock (_backgroundThread)
{
StopWatch._tickCountUpdateRequest.Set();
StopWatch._tickCountUpdateDone.WaitOne();
return CurrentTickCount * 1000 / StopWatch.Frequency;
}
}

/// <summary>
/// Get the time elapsed, in seconds, since the last Reset() or
since
/// creation if Reset() hasn't been called since then.
/// </summary>
/// <returns>Elapsed time in seconds.</returns>
public double GetElapsed_s()
{
lock (_backgroundThread)
{
StopWatch._tickCountUpdateRequest.Set();
StopWatch._tickCountUpdateDone.WaitOne();
return (double)(CurrentTickCount - StartTickCount) /
(double)StopWatch.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>Elapsed time in milliseconds.</returns>
public long GetElapsed_ms()
{
lock (_backgroundThread)
{
StopWatch._tickCountUpdateRequest.Set();
StopWatch._tickCountUpdateDone.WaitOne();
return (CurrentTickCount - StartTickCount) * 1000 /
StopWatch.Frequency;
}
}
}
}

Feb 14 '07 #4
"not_a_commie" <no********@gmail.comwrote in message
news:11*********************@l53g2000cwa.googlegro ups.com...
>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
BeginThreadAffinity 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.Diagnostics;
using System.Threading;

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

static public long Frequency = 0;
static public long CurrentTickCount = 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 _backgroundThreadFunc()
{
Thread.BeginThreadAffinity();
Frequency = System.Diagnostics.Stopwatch.Frequency;
while (true)
{
_tickCountUpdateRequest.WaitOne();
CurrentTickCount = System.Diagnostics.Stopwatch.GetTimestamp();
_tickCountUpdateDone.Set();
}
//Thread.EndThreadAffinity(); // never called
}

/// <summary>
/// The System.Diagnostics.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() {
_backgroundThread = new Thread(new
ThreadStart(_backgroundThreadFunc));
_backgroundThread.IsBackground = true;
_backgroundThread.Start();
}

/// <summary>
/// Initializes a new instance of the StopWatch class.
/// </summary>
/// <exception cref="NotSupportedException">The 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="NotSupportedException">The system does not have
a high-resolution performance counter.</exception>
public void Reset()
{
lock (_backgroundThread)
{
StopWatch._tickCountUpdateRequest.Set();
StopWatch._tickCountUpdateDone.WaitOne();
StartTickCount = CurrentTickCount;
}
}

/// <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.AddSeconds(seconds);
int i = 0;
while (DateTime.Now < endTime) { i++; }
}

public long GetCurrentTime_ms()
{
lock (_backgroundThread)
{
StopWatch._tickCountUpdateRequest.Set();
StopWatch._tickCountUpdateDone.WaitOne();
return CurrentTickCount * 1000 / StopWatch.Frequency;
}
}

/// <summary>
/// Get the time elapsed, in seconds, since the last Reset() or
since
/// creation if Reset() hasn't been called since then.
/// </summary>
/// <returns>Elapsed time in seconds.</returns>
public double GetElapsed_s()
{
lock (_backgroundThread)
{
StopWatch._tickCountUpdateRequest.Set();
StopWatch._tickCountUpdateDone.WaitOne();
return (double)(CurrentTickCount - StartTickCount) /
(double)StopWatch.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>Elapsed time in milliseconds.</returns>
public long GetElapsed_ms()
{
lock (_backgroundThread)
{
StopWatch._tickCountUpdateRequest.Set();
StopWatch._tickCountUpdateDone.WaitOne();
return (CurrentTickCount - StartTickCount) * 1000 /
StopWatch.Frequency;
}
}
}
}

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_commie" <notacom...@gmail.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
BeginThreadAffinity 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.ProcessorAffinity 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
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...
6
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
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...
7
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...
8
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...
3
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...
2
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...
10
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...
23
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
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 ...
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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
0
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,...
0
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...
0
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...
0
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...
0
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...

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.