How to measure precisely CPU usage in Background Tasks?
Asked Answered
N

2

11

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

Notochord answered 27/10, 2012 at 20:10 Comment(4)
I would also guess that an i5 can run more code than an ARM based processor... Will I so need the slowest processor avalible to test if my app will not take more than 2 sec?Anorexia
Good point, if that's right, we have much less computing power for our background work on low-end ARM tablets than on Core-i7 oveclocked desktops.Notochord
Are web workers the same as background tasks? I would like to fetch and cache images, but 2 seconds doesn't seem like enough processing time (especially since I'd like to crop and save them).Photochemistry
Is this a single time task or will it run repeatedly?Adamec
M
0

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.

Madson answered 27/12, 2012 at 23:54 Comment(1)
I guess this is the best we can do right now for measuring the CPU usage, thanks.Notochord
F
0

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.

Flattery answered 30/4, 2016 at 17:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.