473,801 Members | 2,582 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reading thread 'processor time' quickly

Hi,

I need to be able to read the amount of processor time a thread has taken
up. So far I've found the following methods open to me:

1) Find the relevant ProcessThread in the current process'
ProcessThreadCo llection and read the TotalProcessorT ime.

2) Find the PerformanceCoun ter for the Thread category that relates to the
current thread, and use the NextSample() method to read the processor time
value. (I think this is pretty much what the first method is doing under the
hood anyway)

The problem is, both of those approaches are too slow for me, as I need to
find the value many times in quick succession (I'm using this to find out the
performance cost of methods)

From what I can tell about the PerformanceCoun ter approach, it re-gets *all*
the performance counter information for all the running threads and processes
every time I call NextSample, which isn't ideal. Is there any way just read
the value for the performance counter instance I'm actually interested in?

Cheers,
Mike

Nov 22 '05 #1
6 3723
Hi Mike,

First of all, I would like to confirm my understanding of your issue. From
your description, I understand that you need to get the CPU time of a
certain thread. If there is any misunderstandin g, please feel free to let
me know.

As far as I know, we can use both methods you mentioned to get the CPU
time. For the PerformanceCoun ter, we needn't get all the performance
information for all the running threads and processes every time. We can
specify the instance name, category and counter name for the performance
counter object. When we call NextValue method, it only returns the
information we need. Both of the two methods are fast enough on my machine.
Here is an example.

System.Diagnost ics.Performance Counter pc = new
System.Diagnost ics.Performance Counter("Thread ", "% Processor Time");
pc.InstanceName = "WindowsApplica tion82/0";
float f = pc.NextValue();

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Nov 22 '05 #2
Hi Kevin, thanks for your reply

Your understanding is correct, and your example is exactly one of the
approaches I've tried.

Unforfunately some of the methods that I'll need to measure execute very
quickly, and just calling NextValue() takes on average 0.02s-0.03s, which is
too slow for my needs.

I actually think this is a bit of a dead-end anyway, because from what I can
tell, the resolution of the counter seems to be in the centisecond range
anyway - i.e. when I execute it in quick succession, I get the same values
returned, then the reported values jump up by 0.01s.

As a point of note, I used reflector to have a peek to see what was going on
under the hood of the NextValue() method, and from what I could see it has to
re-create the Counter object, parse all of the instance data into a memory
structure and then find the instance I'm interested in. From the looks of
things this is because when you read a counter you get back all the instance
data in one big chunk of memory. (If you can get at the source code, you
will probably be able to see this in the constructor of
System.Diagnost ics.CategorySam ple)

So, unless there is another way of reading thread timings at a higher
resolution, this may be a no-go!

Thanks,
Mike

"Kevin Yu [MSFT]" wrote:
Hi Mike,

First of all, I would like to confirm my understanding of your issue. From
your description, I understand that you need to get the CPU time of a
certain thread. If there is any misunderstandin g, please feel free to let
me know.

As far as I know, we can use both methods you mentioned to get the CPU
time. For the PerformanceCoun ter, we needn't get all the performance
information for all the running threads and processes every time. We can
specify the instance name, category and counter name for the performance
counter object. When we call NextValue method, it only returns the
information we need. Both of the two methods are fast enough on my machine.
Here is an example.

System.Diagnost ics.Performance Counter pc = new
System.Diagnost ics.Performance Counter("Thread ", "% Processor Time");
pc.InstanceName = "WindowsApplica tion82/0";
float f = pc.NextValue();

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Nov 22 '05 #3
Hi Mike,

It seems to be by design that the NextValue takes that much time to execute
in .NET framework. If you need the process to be faster, I think you can
try to use WMI instead, which gets value directly. You can try to post in
microsoft.publi c.win32.program mer.wmi newsgroup for wmi question. There
will be more professionals in that group to answer your question. HTH.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Nov 22 '05 #4
Thanks Kevin, I've used WMI before, so hopefully I'll be able to work this out!

I'll post a quick sample if I get it sorted.

Cheers,
Mike

"Kevin Yu [MSFT]" wrote:
Hi Mike,

It seems to be by design that the NextValue takes that much time to execute
in .NET framework. If you need the process to be faster, I think you can
try to use WMI instead, which gets value directly. You can try to post in
microsoft.publi c.win32.program mer.wmi newsgroup for wmi question. There
will be more professionals in that group to answer your question. HTH.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Nov 22 '05 #5
I promised a sample, so here it is in case anyone else ever wants it - you'll
need to include the System.Manageme nt namespace.

Sadly, the method call still seems to take around the same sort of time as
the performance counter approach - it's slightly faster, but still in the
same sort of ballpark - and the resolution seems to only be down to ~0.0001s.
I admit my needs are fairly extreme, and for most situations this will be
fine - I expect I'll be able to live with it though!

This sample adds together the user mode time and kernel mode time to get the
overall time.

====

string threadId = AppDomain.GetCu rrentThreadId() .ToString();
string processId =
System.Diagnost ics.Process.Get CurrentProcess( ).Id.ToString() ;

using (ManagementObje ct testObject = new
ManagementObjec t(@"\\.\root\ci mv2:Win32_Threa d.Handle=""" + threadId +
"\",ProcessHand le=\"" + processId + "\""))
{
Console.WriteLi ne(((UInt64)tes tObject.Propert ies["UserModeTi me"].Value +
(UInt64)testObj ect.Properties["KernelModeTime "].Value).ToStrin g());
}

=======

Thanks for your time, Kevin,
Mike

"Mike Goatly" wrote:
Thanks Kevin, I've used WMI before, so hopefully I'll be able to work this out!

I'll post a quick sample if I get it sorted.

Cheers,
Mike

"Kevin Yu [MSFT]" wrote:
Hi Mike,

It seems to be by design that the NextValue takes that much time to execute
in .NET framework. If you need the process to be faster, I think you can
try to use WMI instead, which gets value directly. You can try to post in
microsoft.publi c.win32.program mer.wmi newsgroup for wmi question. There
will be more professionals in that group to answer your question. HTH.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Nov 22 '05 #6
You're welcome, Mike.

Thanks for sharing your experience with all the people here. If you have
any questions, please feel free to post them in the community.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Nov 22 '05 #7

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

Similar topics

8
1918
by: Ola Natvig | last post by:
Anybody out there who knows if the 4suite implementation of XSLT are a threadsafe one? -- -------------------------------------- Ola Natvig <ola.natvig@infosense.no> infoSense AS / development
5
459
by: Mike Goatly | last post by:
Hi, I need to be able to read the amount of processor time a thread has taken up. So far I've found the following methods open to me: 1) Find the relevant ProcessThread in the current process' ProcessThreadCollection and read the TotalProcessorTime. 2) Find the PerformanceCounter for the Thread category that relates to the current thread, and use the NextSample() method to read the processor time
1
4475
by: benmorganpowell | last post by:
I have a small windows service which connects to a POP3 server at defined intervals, scans the available messages, extracts the required information and inserts the data into a SQL database. I am assuming that this is not an uncommon piece of software. I want to get an architecture that conforms as closely as possible with the recommendations from Microsoft on developing Windows Services, but to be honest I have found difficultly in...
4
7022
by: kaiteriteri | last post by:
I have a time-consuming VB.net application that i'd like to thread over 2 processors (that's all i've got in my machine!) and, hopefully, get it done in half the time. On running, the application should create a 2nd thread and run it on the other processor (processing a distinct set of data), leaving the current thread to run and process its set of data. But the 2nd thread must run on the free processor, otherwise there's no point... ...
3
1476
by: Joe Befumo | last post by:
This is my first attempt at multi-thread programming, and I'm encountering a program-logic problem that I can't quite put my finger on. The program is pretty simple. I'm trying to validate a large list of email addresses. Since the actual validation can take some time, I'm spawning new threads, up to a predetermined maximum value, to process each new address.
8
2286
by: Joe Withawk | last post by:
I have an application in which there exist a thread that handles directx rendering. It runs on a dual core system with windows vista and xp. It is set to have highest priority and simply loops with while(isRendering) { prepare for rendering; do render; present() }
10
2118
by: sophie_newbie | last post by:
Hi, I'm trying to write a piece of code that spawns a thread and prints dots every half second until the thread spawned is finished. Code is something like this: import threading class MyThread ( threading.Thread ): def run ( self ): myLongCommand()...
29
9152
by: NvrBst | last post by:
I've read a bit online seeing that two writes are not safe, which I understand, but would 1 thread push()'ing and 1 thread pop()'ing be thread-safe? Basically my situation is the follows: --Thread 1-- 1. Reads TCPIP Buffer 2. Adds Buffer to Queue (q.size() to check queue isn't full, and q.push_back(...)) 3. Signals Reading Thread Event & Goes Back to Wait for More Messages on TCPIP
12
2083
by: Ronny | last post by:
Thanks Chris, Looks nice but I miss the dual way communication. In the main thread to deliver paramters and data to the worker thread- how can I do that? Regards Ronny Take a look at the background worker thread component. It has what you want built into it. http://msdn.microsoft.com/en-us/library/8xs8549b.aspx
2
4211
by: poldoga | last post by:
Here is my problem. I have a thread which constantly polls a piece of hardware's serial output. Every time it detects a certain serial sequence, it triggers an event handler wherein I have code which processes said sequence. The problem is that the processing is quite time intensive. I noticed that when the program is in the event handler, the hardware is not being polled. If possible, I would like the processing and polling to happen...
0
10524
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
10298
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
10278
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
10055
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
9105
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
7594
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
6833
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();...
2
3786
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2963
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.