Korrekt cpu-forbrug på processer
høh, det er officielt: jeg har ingen hjerne :D Jeg har prøvet alt muligt, men enten får jeg altid 0, 1 ciffer når der skal være 2 (+ underlige negative tal), eller op til langt over 100 endda over 1000 (+ underlige negative tal), når jeg forsøger at få processers procentandel i cpu-forbrug.Koden er som følger (bærende præg af at jeg har forsøgt alskens ting):
Imports System
Imports System.Diagnostics
Imports System.Threading
Imports System.IO
Imports System.ServiceProcess
Module Module1
Sub Main()
While True
Dim all_processes As Process() = Process.GetProcesses()
Dim p1() As Long = {0.0}
Dim p2() As Long = {0.0}
Dim ptotal As Long = 0.0
Dim t1 As Long = DateTime.Now.Ticks
For index As Integer = 0 To all_processes.Length() - 1
If Not all_processes(index).ProcessName = "Idle" Then
p1(index) = all_processes(index).TotalProcessorTime.Ticks
End If
ReDim Preserve p1(p1.Length())
Next
Thread.Sleep(1000)
Dim t2 As Long = DateTime.Now.Ticks
For index As Integer = 0 To all_processes.Length() - 1
If Not all_processes(index).ProcessName = "Idle" Then
Try
p2(index) = all_processes(index).TotalProcessorTime.Ticks
ReDim Preserve p2(p2.Length())
Catch ex As Exception
Finally
End Try
End If
Next
ptotal = 0.0
For index As Integer = 0 To all_processes.Length() - 1
Try
ptotal += p2(index) - p1(index)
Catch ex As Exception
Finally
End Try
Next
Dim pct As Integer = 0
For index As Integer = 0 To all_processes.Length() - 1
'pct = CInt(((2000 * (p2(index) - p1(index)) \ ptotal) \ (t2 - t1)))
Try
pct = CInt(((1 * (p2(index) - p1(index))) \ ((t2 - t1) - ptotal)) * 1) '* 100)
Catch ex As Exception
Finally
End Try
Console.WriteLine(all_processes(index).ProcessName().ToString + " " + pct.ToString + " " + ptotal.ToString + " " + Str((t2 - t1)) + Str((p2(index) - p1(index))))
Next
End While
End Sub
End Module
Jeg forsøger her også at tage højde for at processer stopper midt i det hele