本文介绍了如何获取每个线程在Windows上的CPU使用率(win32)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
寻找Win32 API函数,C ++或Delphi示例代码,告诉我线程的CPU使用率(百分比和/或总CPU时间)(而不是进程的总和)。我有线程ID。
我知道Sysinternals Process Explorer可以显示这些信息,但我需要程序中的这些信息。
<$ p $ p>
const
THREAD_TERMINATE = $ 0001;
THREAD_SUSPEND_RESUME = $ 0002;
THREAD_GET_CONTEXT = $ 0008;
THREAD_SET_CONTEXT = $ 0010;
THREAD_SET_INFORMATION = $ 0020;
THREAD_QUERY_INFORMATION = $ 0040;
THREAD_SET_THREAD_TOKEN = $ 0080;
THREAD_IMPERSONATE = $ 0100;
THREAD_DIRECT_IMPERSONATION = $ 0200;
THREAD_SET_LIMITED_INFORMATION = $ 0400;
THREAD_QUERY_LIMITED_INFORMATION = $ 0800;
THREAD_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED或SYNCHRONIZE或$ 03FF;
function OpenThread(dwDesiredAccess:DWord;
bInheritHandle:Bool;
dwThreadId:DWord):DWord; stdcall; external'kernel32.dll';
procedure TForm1.Button1Click(Sender:TObject);
var iii:integer;
handle:thandle;
creationtime,exittime,kerneltime,usertime:filetime;
begin
Handle:= OpenThread(THREAD_SET_INFORMATION或THREAD_QUERY_INFORMATION,False,windows.GetCurrentThreadId);
if handle<> 0 then
begin
getthreadtimes(Handle,creationtime,exittime,kerneltime,usertime);
label1.caption:='线程的总时间#'+ inttostr(windows.GetCurrentThreadId)+':'+ inttostr((int64(kerneltime)+ int64(usertime))div 1000)+'msec';
CloseHandle(Handle);
end;
end;
Looking for Win32 API functions, C++ or Delphi sample code that tells me the CPU usage (percent and/or total CPU time) of a thread (not the total for a process). I have the thread ID.
I know that Sysinternals Process Explorer can display this information, but I need this information inside my program.
解决方案
With the help of RRUZ's answer above I finally came up with this code for Borland Delphi:
const
THREAD_TERMINATE = $0001;
THREAD_SUSPEND_RESUME = $0002;
THREAD_GET_CONTEXT = $0008;
THREAD_SET_CONTEXT = $0010;
THREAD_SET_INFORMATION = $0020;
THREAD_QUERY_INFORMATION = $0040;
THREAD_SET_THREAD_TOKEN = $0080;
THREAD_IMPERSONATE = $0100;
THREAD_DIRECT_IMPERSONATION = $0200;
THREAD_SET_LIMITED_INFORMATION = $0400;
THREAD_QUERY_LIMITED_INFORMATION = $0800;
THREAD_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED or SYNCHRONIZE or $03FF;
function OpenThread(dwDesiredAccess: DWord;
bInheritHandle: Bool;
dwThreadId: DWord): DWord; stdcall; external 'kernel32.dll';
procedure TForm1.Button1Click(Sender: TObject);
var iii:integer;
handle:thandle;
creationtime,exittime,kerneltime,usertime:filetime;
begin
Handle:=OpenThread(THREAD_SET_INFORMATION or THREAD_QUERY_INFORMATION, False, windows.GetCurrentThreadId);
if handle<>0 then
begin
getthreadtimes(Handle,creationtime,exittime,kerneltime,usertime);
label1.caption:='Total time for Thread #'+inttostr(windows.GetCurrentThreadId)+': '+inttostr( (int64(kerneltime)+int64(usertime)) div 1000 )+' msec';
CloseHandle(Handle);
end;
end;
这篇关于如何获取每个线程在Windows上的CPU使用率(win32)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!