【问题标题】:Use Environment.Tickcount to determine how long a computer has been on使用 Environment.Tickcount 确定计算机已开启多长时间
【发布时间】:2014-07-18 14:57:20
【问题描述】:

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

为此,我有这个代码。

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

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

【问题讨论】:

  • Environment.TickCount 是一个 32 位有符号整数,因此只会给你 24.9 天的正常运行时间。我相信有人可以提出更好的方法。
  • 相关帖子here.

标签: sql vb.net wmi


【解决方案1】:

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

Windows 以多种方式报告该值:作为kernel32 中的GetTickCount64,它是PerformanceCounter,它位于WMI。它仅报告自上次重新启动以来的系统运行时间。如果上一次重启是一周前,如果净睡 2 天,它可能只报告 5 天,所以它是近似值。

这是有道理的,因为在睡眠/休眠/待机时不能说系统处于“启动”状态。 TaskManager 性能选项卡:

Friend 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

使用它:

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() 提供更好的分辨率,但它仍然是近似值,具体取决于睡眠时间。

【讨论】:

    猜你喜欢
    • 2021-08-14
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    相关资源
    最近更新 更多