CPU usage quota for Background Tasks in WinRT is 1 second, or 2 seconds if they are on lockscreen. The question is how to measure accurately this CPU usage - I'd like to know if my code runs under this 2 sec quota or not? I guess using just DateTime.Now before and after the execution of the task is not the right approach.
The MSDN article about Background Tasks:
Supporting your app with background tasks
2 Answers
I had the same problem.
If you start Task Manager, under the App history tab, you can see the statistics of Resource usage by various apps. One of them is CPU Time. The problem is that it's not the average, but it only displays the total CPU usage time.
If you need the average time, the trick is to keep a count in your app for any background activity, and divide the whole time by that, so you will get an average time.
I used GetProcessTimes WinAPI.
The documentation says “desktop apps only”, but technically, it is present even on the phones:
[DllImport( "KERNELBASE.DLL", SetLastError = true )]
static extern IntPtr GetCurrentProcess();
// NB! Undocumented API, won't pass marketplace checks.
[DllImport( "KERNELBASE.DLL", SetLastError = true )]
[return: MarshalAs( UnmanagedType.Bool )]
static extern bool GetProcessTimes( IntPtr hProcess, out long lpCreationTime, out long lpExitTime, out long lpKernelTime, out long lpUserTime );
On the PC replace KERNELBASE.DLL with Kernel32.dll.
That won’t pass marketplace certification, but should be enough for you to benchmark your background task.
Call GetProcessTimes when started, calculate long startTime = KernelTime + UserTime. Call GetProcessTimes when finished, calculate ( KernelTime + UserTime ) - startTime, and you get your data. The unit of measure is 100ns ticks, just like in TimeSpan.