使用Environment.Tickcount确定计算机已运行多长时间

时间:2014-07-18 14:57:20

标签: sql vb.net wmi

我一直在研究一个项目,在这个项目中,我需要大致了解计算机已经运行了多长时间。

为此,我有这个代码。

TimeSpan.FromMilliseconds(Environment.TickCount).ToString("dd:hh:mm:ss:ff")有人可以证实这很好吗?

上述格式的sql需要什么数据类型? 感谢

1 个答案:

答案 0 :(得分:2)

a rough idea of how long a computer has been on:

Windows会报告各种方式:GetTickCount64来自kernel32PerformanceCounterWMIFriend Shared Function GetWMIItem(wmiclass As String, qItem As String) As String Dim retVal As String = "" Dim query = String.Format("SELECT {0} FROM {1}", qItem, wmiclass) Using searcher As New ManagementObjectSearcher(query) For Each item As ManagementObject In searcher.Get Dim p = item.Properties(qItem) If (p IsNot Nothing) AndAlso (p.Value IsNot Nothing) Then retVal = p.Value.ToString ' should be nothing else Exit For End If Next End Using Return retVal End Function 。它仅报告自上次重新引导以来的系统运行时间。如果最后一次重新启动是一周前,如果花费2天的时间用于休眠,它可能只报告5天,所以它是近似值。

这是有道理的,因为系统不能说是" up"睡觉/冬眠/待命时。 TaskManager性能选项卡:

enter image description here

Dim uptime = WMI.GetWMIItem("Win32_PerfFormattedData_PerfOS_System",
               "SystemUpTime")
Dim tsUp = TimeSpan.FromSeconds(Convert.ToInt32(uptime))

使用它:

Dim lastBootStrVal = WMI.GetWMIItem("Win32_OperatingSystem", "LastBootUpTime")

返回是秒,而不是毫秒。如果您需要上次启动时间:

dtLastBoot = Management.ManagementDateTimeConverter.ToDateTime(LastBootTimeString)

要阅读它,有一个特殊的转换器,因为它是一种特殊的格式:

PerformanceCounter

使用Using uptime As New PerformanceCounter("System", "System Up Time") ' need to call NextValue once before using a PerformanceCounter uptime.NextValue ts = TimeSpan.FromSeconds(Convert.ToDouble(uptime.NextValue)) End Using 的代码较少(请参阅评论中的链接),但速度一样慢:

GetTickCount64()

否则它们都是相同的,{{1}}提供更好的分辨率,但它仍然是近似值,具体取决于睡眠时间。