Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 以UWP应用程序Windows 10 IOT的百分比计算CPU使用率_C#_Uwp_Cpu Usage_Windows 10 Iot Core - Fatal编程技术网

C# 以UWP应用程序Windows 10 IOT的百分比计算CPU使用率

C# 以UWP应用程序Windows 10 IOT的百分比计算CPU使用率,c#,uwp,cpu-usage,windows-10-iot-core,C#,Uwp,Cpu Usage,Windows 10 Iot Core,我想计算CPU使用率的百分比。目前我正在使用ProcessDiagnosticInfo获取内核时间和用户时间。我如何将这段时间转换为百分比,或者建议我使用任何其他方法来查找它(如果有) private TimeSpan GetTotalCpuTime() { var totalKernelTime = new TimeSpan(); var totalUserTime = new TimeSpan(); var pdis = Proces

我想计算CPU使用率的百分比。目前我正在使用
ProcessDiagnosticInfo
获取内核时间和用户时间。我如何将这段时间转换为百分比,或者建议我使用任何其他方法来查找它(如果有)

private TimeSpan GetTotalCpuTime()
    {
        var totalKernelTime = new TimeSpan();
        var totalUserTime = new TimeSpan();

        var pdis = ProcessDiagnosticInfo.GetForProcesses();
        foreach (var pdi in pdis)
        {
            var cpuUsage = pdi.CpuUsage;
            var report = cpuUsage.GetReport();
            totalKernelTime += report.KernelTime;
            totalUserTime += report.UserTime;
        }

        return totalKernelTime + totalUserTime;
    }

我还知道Windows 10 IoT仪表板API“/API/resourcemanager/systemperf”,它返回系统统计数据,其中包括CPU使用百分比,但访问它需要凭据,因此我不想使用它。

每个进程在内核模式下花费一些时间,在用户模式下花费一些时间。需要注意的是,我们没有考虑空闲时间。 请参考以下代码

    private static readonly Stopwatch Stopwatch = new Stopwatch();
    private static TimeSpan _oldElapsed, _oldKernelTime, _oldUserTime;
    private static int ProcessorCount { get; }
    private static double _carryOver;

    static CpuUsage()
    {
        // Stopwatch will be used to track how much time/usage has elapsed.
        Stopwatch.Start();
        // We'll divide the total used CPU time by the number of processors.
        ProcessorCount = System.Environment.ProcessorCount;
        // Run to store the initial "oldKernel/UserTime" so the first read 
        // isn't super inflated by the application's start-up.
        GetTotalCpuTime();
    }

    /// <summary>
    /// Returns the average percentage of CPU time used since the last time this call was made.
    /// </summary>
    /// <returns></returns>
    private static TimeSpan GetTotalCpuTime()
    {
        // Because we could have more than one process running, add all of them up.
        var totalKernelTime = new TimeSpan();
        var totalUserTime = new TimeSpan();

        // Grab the diagnostic infos for all existing processes.
        var pdis = ProcessDiagnosticInfo.GetForProcesses();
        foreach (var pdi in pdis)
        {
            var cpuUsage = pdi.CpuUsage;
            var report = cpuUsage.GetReport();
            totalKernelTime += report.KernelTime;
            totalUserTime += report.UserTime;
        }

        // Subtract the amount of "Total CPU Time" that was previously calculated.
        var elapsedKernelTime = totalKernelTime - _oldKernelTime;
        var elapsedUserTime = totalUserTime - _oldUserTime;

        // Track the "old" variables.
        _oldKernelTime = totalKernelTime;
        _oldUserTime = totalUserTime;

        // Between both is all of the CPU time that's been consumed by the application.
        return elapsedKernelTime + elapsedUserTime;
    }

    public static double GetPercentage()
    {
        // Because there's a small amount of time between when the "elapsed" is grabbed, 
        // and all of the process KernelTime and UserTimes are tallied, the overall CPU
        // usage will be off by a fraction of a percent, but it's nominal.  Like in the 
        // 0.001% range.
        var elapsed = Stopwatch.Elapsed;
        var elapsedTime = elapsed - _oldElapsed;

        var elapsedCpuTime = GetTotalCpuTime();

        // Divide the result by the amount of time that's elapsed since the last check to 
        // get the percentage of CPU time that has been consumed by this application.
        var ret = elapsedCpuTime / elapsedTime / ProcessorCount * 100;

        // Track the "old" variables.
        _oldElapsed = elapsed;

        // This part is completely optional.  Because the thread could be called between 
        // the time that "elapsed" is grabbed, and the CPU times are calculated, this will
        // cause a "pause" that results in spiking the "CPU usage time" over 100%.  However
        // on the next call, the difference will be "lost" (so if it the CPU percent was
        // at 100% for two calls, but this 'pause' happened, one could report 150% while
        // the next would report 50%.)  By carrying over the values above 100%, we can get
        // a slightly more accurate "average" usage.  
        ret += _carryOver;
        if (ret > 100)
        {
            _carryOver = ret - 100;
            ret = 100;
        }
        else
        {
            _carryOver = 0;
        }

        return ret;
    }
private static readonly Stopwatch Stopwatch=new Stopwatch();
私有静态时间跨度_oldEssed、_oldKernelTime、_oldUserTime;
私有静态int处理器计数{get;}
私人静态双结转;
静态CpuUsage()
{
//秒表将用于跟踪经过的时间/使用量。
秒表。开始();
//我们将使用的CPU总时间除以处理器的数量。
ProcessorCount=System.Environment.ProcessorCount;
//运行以存储初始“oldKernel/UserTime”,以便第一次读取
//不会因应用程序的启动而过度膨胀。
gettotalputime();
}
/// 
///返回自上次调用以来使用的CPU时间的平均百分比。
/// 
/// 
私有静态TimeSpan GetTotalComputime()
{
//因为我们可以运行多个进程,所以将所有进程相加。
var totalKernelTime=new TimeSpan();
var totalUserTime=new TimeSpan();
//获取所有现有流程的诊断信息。
var pdis=ProcessDiagnosticInfo.getforprocesss();
foreach(pdi中的var pdi)
{
var cpuUsage=pdi.cpuUsage;
var report=cpuUsage.GetReport();
totalKernelTime+=report.KernelTime;
totalUserTime+=report.UserTime;
}
//减去之前计算的“总CPU时间”。
var elapsedKernelTime=总KernelTime-_oldKernelTime;
var elapsedUserTime=totalUserTime-\u oldUserTime;
//跟踪“旧”变量。
_oldKernelTime=总KernelTime;
_oldUserTime=总用户时间;
//两者之间是应用程序消耗的所有CPU时间。
返回elapsedKernelTime+elapsedUserTime;
}
公共静态双GetPercentage()
{
//因为在抓取“经过的”之间有一小段时间,
//所有进程的内核时间和用户时间都被统计,整个CPU
//使用率将下降百分之一,但这是名义上的。就像在
//0.001%范围。
var已用=秒表已用;
var elapsedTime=已用时间-\u oldpeased;
var elapsedCpuTime=gettotalputime();
//将结果除以自上次检查到之后经过的时间量
//获取此应用程序已占用的CPU时间百分比。
var ret=elapsedCpuTime/elapsedTime/ProcessorCount*100;
//跟踪“旧”变量。
_oldpeased=经过;
//这部分是完全可选的。因为线程可以在
//抓取“经过”的时间,并计算CPU时间,这将
//导致“暂停”,导致“CPU使用时间”超过100%。但是
//在下一次调用中,差异将“丢失”(因此,如果它是CPU百分比)
//两个电话的通话率为100%,但这种“暂停”发生了,其中一个电话的通话率为150%
//下一个将报告50%)通过将值转移到100%以上,我们可以得到
//略为精确的“平均”用法。
ret+=\u结转;
如果(ret>100)
{
_结转率=ret-100;
ret=100;
}
其他的
{
_结转率=0;
}
返回ret;
}
更新: 您需要在清单中声明appDiagnosticspackageQuery功能

  • appDiagnostics功能允许应用程序获取诊断信息 信息
  • packageQuery设备功能允许应用程序 收集有关其他应用程序的信息
*.appxmanifest

  <Capabilities>
    <Capability Name="internetClient" />
    <rescap:Capability Name="appDiagnostics" />
    <rescap:Capability Name="packageQuery" />
  </Capabilities>


这里有一个关于,希望对你有所帮助。此外,您可以参考此信息。

嗨,朋友,我已经更新了此问题的答案。如果有任何问题,请随时告诉我。此外,
SystemDiagnosticInfo.GetForCurrentSystem().CpuUsage.GetReport()
还可用于获取系统CPU使用率。