Visual C++: How to get the CPU time?

2019-08-03 06:22发布

问题:

How can I programatically find the CPU time which is displayed in System Idle Process (in Task Manager) using Visual C++?

回答1:

What you want is something like this...

NTSTATUS hStatus;
SYSTEM_PERFORMANCE_INFORMATION             stSysPerfInfo;

hStatus = NtQuerySystemInformation(SystemPerformanceInformation, &stSysPerfInfo, sizeof(stSysPerfInfo), NULL);
if (hStatus != NO_ERROR)
{
  // Do work....
}

Or take a look at this "TaskManager"

http://reactos.freedoors.org/Reactos%200.3.8/ReactOS-0.3.8-REL-src/base/applications/taskmgr/



回答2:

I don't have a windows around to really know what the question is, but maybe you can look into the std::clock standard function for measuring spent cpu time. If you request that time twice, the amount of ticks in the elapsed time period can be converted to seconds through the constant CLOCKS_PER_SEC.

The result will be the CPU time your process has spent, that will differ from a wall clock. It can be higher in multithreaded apps, or lower if your code _sleep_s, as it will not be spending time.

void f()
{
   std::clock_t init = std::clock();
   // perform some operations
   std::clock_t end = std::clock();
   std::cout << end-init << " cpu ticks spent, or about " 
             << (end-init)/CLOCKS_PER_SEC << " seconds." << std::endl;
}

This will not count for the CPU time before the first measurement, but it can give you a close measurement in an standard way.



回答3:

Never tried it, but GetProcessTimes seems to be the way to go.



回答4:

I'd use the WMI Performance Counters, specifically Process/%ProcessorTime/Idle.

Read this Article for how to do it in C# http://www.codeproject.com/KB/dotnet/perfcounter.aspx

and in C++: http://msdn.microsoft.com/en-us/library/aa394558(VS.85).aspx

Hope this answers your question.



回答5:

Also see my post on this: http://osequal.blogspot.com/2009/03/accurate-time-measurement-for.html . In particular, check the implementation of tick_count in Intel TBB library: http://cc.in2p3.fr/doc/INTEL/tbb/doc/html/a00199.html