We help IT Professionals succeed at work.

Cpu Usage.

marcoo asked
Medium Priority
Last Modified: 2007-11-27

I'm building an application in VB. That communicates with windows media encoder.

I want to access the Cpu Usage on the machine. But can't find the correct API call.
That's my problem!

Watch Question


you can try this sample to monitor process 0 - system idle time

The Black Art of Benchmarking

Benchmarking is one of the most complex problems in computer science, in part because it is often difficult to figure out exactly what you are measuring. This is especially challenging in a preemptive multitasking operating system. Because the resolution of the internal system timers is limited, one common technique for measuring performance of a piece of code is to run it multiple times and measure the total elapsed time. An easy way to calculate times is to use the GetTickCount function, which returns the number of milliseconds since the system was started?simply record the value at the beginning of the routine, run the code you wish to measure inside a loop, then measure the time again and compare with the original time. This works nicely on Windows 3.1, but in a preemptive multitasking system such as Windows 95 or Windows NT, this elapsed time will also include time spent running other applications and system services. This can compromise the accuracy of the measurements.

Fortunately, Win32 under Windows NT provides a mechanism for determining exactly how much time is being spent within a given process. This is accomplished with the GetProcessTimes function. This function loads various timing parameters for a process into a set of FILETIME structures. The FILETIME structure is defined as follows:

Private Type FILETIME
        dwLowDateTime As Long
        dwHighDateTime As Long
End Type

The two long variables combine to form a single 64-bit number that represents a time specified in 100-nanosecond increments. This is far more resolution than you are likely to need, and more than most systems can provide at this time, but at least one cannot accuse Microsoft of not thinking ahead. Still, as you will see, working with this type of structure poses its own unique challenges.
The GetProcessTimes function is defined as follows:

Declare Function GetProcessTimes Lib "kernel32" (ByVal hProcess As Long, lpCreationTime As FILETIME, lpExitTime As FILETIME, lpKernelTime As

The first parameter is a handle to the process. lpCreationTime references a FILETIME structure that will be loaded with the time that the process was started, and lpExitTime references a structure that will be loaded with the time that it was terminated (or an undefined value if the process is still running). To understand the lpKernelTime and lpUserTime you will need to know a little bit more about how Windows itself works. One of the ways that 32-bit Windows protects applications from interfering with each other is to isolate them in their own memory space. But how can an operating system really prevent an application from accessing all of the system?s resources? After all, each application can access the same low-level computer instructions as the operating system?what?s to stop them from executing the same commands that the operating system itself uses to manage applications and the system as a whole?

Clearly it couldn?t, if the assumption about each application having access to all of a computer?s instructions was accurate. As it turns out, the system processor used to support Win32 operating systems must be able to support two different modes. Kernel mode (also known as ?privileged? mode) is the one used by the operating system itself. In this mode, all of the CPU?s instructions are available. A second mode called User mode (nonprivileged) locks out a number of critical CPU instructions. This mode is used by applications and most system services. If an application tries to access one of the privileged instructions, an exception occurs and operating system code takes over.

Each process spends some time in user mode, but will also spend time in kernel mode when it is executing operating system code?which happens frequently during API calls. On a single tasking system, the total elapsed time for an application would equal the sum of the user time and the kernel time. As you will see, the total elapsed time in the examples shown in this chapter will exceed this value?the difference is time spent running other processes or system services.
In order to support these types of measurements, a simple benchmarking class was developed, portions of which are shown in Listing 19.1.

Listing 19.1      dwBench.vbp



  MultiUse = -1  'True


Attribute VB_Name = "dwBenchMark"

Attribute VB_Creatable = True

Attribute VB_Exposed = True

' dwBenchMark - Benchmarking utility class

' Part of the Desaware API Class Library

' Copyright (c) 1996 by Desaware.

' All Rights Reserved

Option Explicit

Private Declare Function GetProcessTimes Lib "kernel32" (ByVal hProcess As Long, _

lpCreationTime As FILETIME, lpExitTime As FILETIME, lpKernelTime As FILETIME, _

lpUserTime As FILETIME) As Long

Private Declare Function GetTickCount Lib "kernel32" () As Long

Private Declare Function GetCurrentProcess Lib "kernel32" () As Long

Private Type FILETIME

        dwLowDateTime As Long

        dwHighDateTime As Long

End Type

' This is the reference user time as marked.

Private ReferenceTime As FILETIME

' This is the marked user time for comparisons.

Private MarkTime As FILETIME

' This is the reference kernel time as marked.

Private ReferenceKTime As FILETIME

' This is the marked kernel time for comparisons.

Private MarkKTime As FILETIME

' Reference TickCount

Private ReferenceTick As Long

' The marked tick count for comparisons

Private MarkTick As Long

' A variable to hold the current process handle to use

Private ThisProcess As Long

' Dummy filetime structures that we won't actually use

Private fcreate As FILETIME

Private fexit As FILETIME

Private Sub Class_Initialize()

    ' There is no need to close this pseudo handle

    ThisProcess = GetCurrentProcess()

End Sub

' Sets the reference time

Public Sub SetReference()

    ReferenceTick = GetTickCount

    Call GetProcessTimes(ThisProcess, fcreate, fexit, ReferenceKTime, ReferenceTime)

End Sub

' Sets the mark time

Public Sub SetMark()

    MarkTick = GetTickCount

    Call GetProcessTimes(ThisProcess, fcreate, fexit, MarkKTime, MarkTime)

End Sub

' Subtracts MarkTime from ReferenceTime and returns the difference

Private Function CalculateDifference(ByVal timespec As Integer) As FILETIME

    Dim f As FILETIME

    Select Case timespec

        Case ?  ' User time

                Call agSubtractFileTimes(MarkTime, ReferenceTime, f)

        Case 1  ' Kernel time

                Call agSubtractFileTimes(MarkKTime, ReferenceKTime, f)

    End Select

    CalculateDifference = f

End Function

' Get the difference based on the tick count in ms

Public Function GetTickDifference() As Long

    GetTickDifference = MarkTick - ReferenceTick

End Function

' Get the difference based on user time in ms

Public Function GetuserDifferenceMS() As Double

    Dim diff As FILETIME

    Dim res As Double

    diff = CalculateDifference(?)

    res = diff.dwLowDateTime / 1????

    If diff.dwHighDateTime <> ? Then

        ' Add in the number of milliseconds for each high count

        res = res + diff.dwHighDateTime * 42949.67296

    End If

    GetuserDifferenceMS = res

End Function

Public Function GetkernelDifferenceMS() As Double

    Dim diff As FILETIME

    Dim res As Double

    diff = CalculateDifference(1)

    res = diff.dwLowDateTime / 1????

    If diff.dwHighDateTime <> ? Then

        ' Add in the number of milliseconds for each high count

        res = res + diff.dwHighDateTime * 42949.67296

    End If

    GetkernelDifferenceMS = res

End Function

There are a few subtle aspects of this code that deserve further attention. The CalculateDifference function subtracts one FILETIME structure from another. Doing this in Visual Basic is quite tricky because VB does not support unsigned variables. This means that the relatively simple task of subtracting one long from another, determining if a carry is required, then subtracting the high order long fields, becomes a rather complex operation that must consider the signs of each variable and trap for overflow conditions as well. Being rather lazy, it seemed to me far easier to implement this subtraction operation using the C language (which includes unsigned integers), so it is now part of the APIGID32.DLL dynamic link library included with this book.

The GetuserDifferenceMS() and GetkernelDifferenceMS() functions perform a rather odd calculation to convert a FILETIME structure into milliseconds. Keep in mind that this structure actually corresponds to a 64-bit value that measures 100ns units. To convert to milliseconds, you must divide this number by 10,000. Going back to basic number theory:

Elapsed time = dwHighDateTime * 2^32 + dwLowDateTime

To divide by 10,000 we have:

(dwHighDateTime * 2^32 + dwLowDateTime)/1???? =

dwHighDateTime * 2^32/1???? + dwLowDateTime/1???? =

dwHighDateTime * 42949.67296 + dwLowDateTime/1????

which is the calculation actually performed by the function.

If the user and kernel times are so valuable, why does the benchmarking class use the ?tick count? elapsed time as well? An obvious reason is that the GetProcessTimes function is not implemented under Windows 95. But another reason is that total elapsed time can become useful when testing functionality that involves more than one process. For example, if you wanted to measure the performance of code that accesses an out-of-process OLE server, you would find that the process time functions do not include time spent in the OLE server?the process is suspended while it is waiting for the server to complete its operation and the elapsed time does not count as part of the process time. You could, perhaps, perform separate time measurements within the OLE server, but this presumes that you have access to the server code, and it still will not take into account overhead time spent within the server itself. In cases like this the total elapsed time can give a better indication of the overall code performance.

Elapsed time is also important for graphic operations which, under Windows NT, can occur in the background while your process is suspended. In cases like these the elapsed time can be substantially longer than the time spent within the process. Because of architectural differences between operating systems, it is crucial that you benchmark your application on all of the systems that you target.

You have 2 hints:
  1.Count all proccesses on local machine than use API fnc. GetProcessTimes for each one.

  2. Learn the topic about WIN utilities (CPU Usage Meter):
Try one of these

Display CPU Usage (Windows 9x Only)

Get CPU Information Using Windows Management Interface (WMI)

Get Local System Info Using Windows Management Interface (WMI)

Good Luck
ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.  Moderators Computer101 or Netminder will return to finalize these if still open in seven days.  Please post closing recommendations before that time.

Question(s) below appears to have been abandoned. Your options are:
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you. You must tell the participants why you wish to do this, and allow for Expert response.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question. Again, please comment to advise the other participants why you wish to do this.

For special handling needs, please post a zero point question in the link below and include the question QID/link(s) that it regards.
Please click the Help Desk link on the left for Member Guidelines, Member Agreement and the Question/Answer process.  http://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp

Please click you Member Profile to view your question history and keep them all current with updates as the collaboration effort continues, to track all your open and locked questions at this site.  If you are an EE Pro user, use the Power Search option to find them.  Anytime you have questions which are LOCKED with a Proposed Answer but does not serve your needs, please reject it and add comments as to why.  In addition, when you do grade the question, if the grade is less than an A, please add a comment as to why.  This helps all involved, as well as future persons who may access this item in the future to seek help.

To view your open questions, please click the following link(s) and keep them all current with updates.

To view your locked questions, please click the following link(s) and evaluate the proposed answer.

------------>  EXPERTS:  Please leave any comments regarding your closing recommendations if this item remains inactive another seven (7) days.  Also, if you are interested in the cleanup effort, please click this link http://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=commspt&qid=20274643

Moderators will finalize this question if still open in 7 days, by either moving this to the PAQ (Previously Asked Questions) at zero points, deleting it or awarding expert(s) when recommendations are made, or an independent determination can be made.  Expert input is always appreciated to determine the fair outcome.
Thank you everyone.
Moderator @ Experts Exchange

P.S.  For any year 2000 questions, special attention is needed to ensure the first correct response is awarded, since they are not in the comment date order, but rather in Member ID order.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.