Runtime: Getting CPU/Memory usage from a .NET Core App

Created on 5 Jan 2018  路  6Comments  路  Source: dotnet/runtime

Hi,

Right now in our application in .NET 4.x, we get the CPU and Memory usage from the machine using performance counters. But of course this works only on Windows.

In .NET Core we are only able to leverage the data from GC.GetTotalMemory, but it only return the memory consumed by our app, not by all processes on the machine.

What would be the best "cross-platform" way to do this using .NET Core?

area-System.Diagnostics.Tracing question

Most helpful comment

You can use at the OS level memory and CPU time usage in a cross platform way by using the APIs in System.Diagnostics.Process. In for example to get the current processes working set and CPU time you can use:

            var me = Process.GetCurrentProcess();
            Console.WriteLine("Working set {0} bytes", me.WorkingSet64);
            Console.WriteLine("Total CPU time {0} sec", me.TotalProcessorTime.TotalSeconds);

You can access this data for other processes using the Process.GetProcesses() or Process.GetProcessById() or GetProcessesByName() APIs to find the process of interest and then fetching the metrics desired.

Is that sufficient?

All 6 comments

@vancem any thoughts?

You can use at the OS level memory and CPU time usage in a cross platform way by using the APIs in System.Diagnostics.Process. In for example to get the current processes working set and CPU time you can use:

            var me = Process.GetCurrentProcess();
            Console.WriteLine("Working set {0} bytes", me.WorkingSet64);
            Console.WriteLine("Total CPU time {0} sec", me.TotalProcessorTime.TotalSeconds);

You can access this data for other processes using the Process.GetProcesses() or Process.GetProcessById() or GetProcessesByName() APIs to find the process of interest and then fetching the metrics desired.

Is that sufficient?

So to get CPU/Mem info for the current machine, we would have to list all processes with Process.GetProcesses and then aggregate CPU time and working set to get a global value?

I think it could work, but I don't know how expensive it would be to list all processes. But we can give a try.

Thanks!

@benjaminpetit Did you end up summing up all the usages across all the processes or did you find a better API to give you the CPU usage and RAM usage?

For the moment we didn't implemented anything. Still waiting to see if we can have a better API...

foreach (var aProc in Process.GetProcesses())
totalsize += aProc.WorkingSet64/1024.0;

i am doing this for my work, it takes ~30-40msec execution time.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

v0l picture v0l  路  3Comments

GitAntoinee picture GitAntoinee  路  3Comments

nalywa picture nalywa  路  3Comments

chunseoklee picture chunseoklee  路  3Comments

aggieben picture aggieben  路  3Comments