How to get percent of using CPU

Hi, I have a question
The LXD API uses these numbers for CPU usage. How do you calculate the actual percentage of use from this? cpu: { usage: 14181382785 }

So you cant do it purely from the API

private async Task<double> GetCPU(string container)
    {
        string state_s = GetContainerState(container);
        JObject state = JObject.Parse(state_s);
        string container_s = GetContainer(container);
        JObject containerObject = JObject.Parse(container_s);
        var startTime = DateTime.UtcNow;
        double startCpuUsage = Math.Ceiling(state.SelectLong("metadata.cpu.usage") / 1000000d);
        await Task.Delay(500);
        state_s = GetContainerState(container);
        state = JObject.Parse(state_s);
        var endTime = DateTime.UtcNow;
        double endCpuUsage = Math.Ceiling(state.SelectLong("metadata.cpu.usage") / 1000000d);
        var cpuUsedMs = (endCpuUsage - startCpuUsage);
        var totalMsPassed = (endTime - startTime).TotalMilliseconds;
        var cpuUsageTotal = cpuUsedMs / ((containerObject.SelectInt("metadata.config.['limits.cpu']") < 1 ? Environment.ProcessorCount : containerObject.SelectInt("metadata.config.['limits.cpu']")) * totalMsPassed);
        return cpuUsageTotal;
    }

I came up with this based on some code i found on stack overflow. Works from what i can tell (i set a limit of 50% on a container, ran a fork bomb in it, and the method returned 50%)

Nice :heart_eyes:

Can I “steal” this ?

yeah of course, obviously if you arent writing C# you’ll have to adapt it for you language, but feel free to use it however

Thank you!

This comment on github seems to suggest a slightly different approach

usage_in_nanoseconds / (capacity_in_absolute_cores * 1e+9).

Yours seem to a slightly different path, would you mind explaining the difference, yours seems a little more developed ?

Mine takes a measurement of the cpu time, waits 500 ms, and measures it again, so we know there is an interval of 500ms (more or less, API requests are included in the timings), and we know the CPU usage in the same time, so from there its just used time divided by the amount of cores times how much time passed. The code in that github link works it out by dividing the cpu time by the amount of nanoseconds in a second, times the number of cores. The premise of this is that any program with 100% usage will have a CPU usage of 1s, so by using this division, the percentage of this can be calculated. This does depend on how LXD and kubernetes each calculate cpu usage time, so im not sure if this will work or not but will probably mess around with it later as it is definitley more efficient then my approach