C #을 사용하여 시스템 가동 시간 검색
C #을 사용하여 시스템 가동 시간을 얻는 간단한 방법이 있습니까?
public TimeSpan UpTime {
get {
using (var uptime = new PerformanceCounter("System", "System Up Time")) {
uptime.NextValue(); //Call this an extra time before reading its value
return TimeSpan.FromSeconds(uptime.NextValue());
}
}
}
조금 늦었지만 또 다른 간단한 방법은 Windows Vista부터 사용할 수 있으며 GetTickCount처럼 오버플로되지 않는 GetTickCount64 함수 를 사용하는 것입니다 .
public static TimeSpan GetUpTime()
{
return TimeSpan.FromMilliseconds(GetTickCount64());
}
[DllImport("kernel32")]
extern static UInt64 GetTickCount64();
System.Environment.TickCount 는 시스템이 다시 시작된 이후의 밀리 초 수를 가져옵니다.
Int32이고 24.9 일 후에 오버플로되어 음수가됩니다. MDSN 문서에 대한 설명을 참조하십시오.
내 컴퓨터는 58 days 17 hours
작업 관리자 에 따라 가동 시간이 있습니다. 필자는 여기에서 각 답변을 시도했고 빠른 답변은 약간 차이가 있습니다 (대략 1 ~ 3 분이지만 가동 시간은 58 일 이상입니다).
Stopwatch.GetTimeStamp(): 58days 17hours 11minutes 25seconds
~Time to calculate (ms): 6.8413
DllImport GetTickCount64(): 58days 17hours 13minutes 34seconds
~Time to calculate (ms): 0.2192
PerformanceCounter(System, System Up Time): 58days 17hours 14minutes 02seconds
~Time to calculate (ms): 1233.2854
ManagementObject LastBootUpTime: 58days 17hours 14minutes 02seconds
~Time to calculate (ms): 30.0283
PerformanceCounter를 사용하거나 ManagementObject를 사용하는 마지막 두 개는 항상 Windows 작업 관리자와 같은 시간 내에 있습니다 (제 말을 그대로 사용하거나 아래 코드를 사용하여 직접 시도해보세요). 결과를 바탕으로이 ManagementObject LastBootUpTime
방법 을 사용할 것입니다. 왜냐하면 PerformanceCounter
작업 관리자와 비교할 때 훨씬 더 빠르지 만 여전히 완벽하게 정확하기 때문입니다.
시간을 인쇄하기 전에 각 방법에서 현재 경과 시간을 뺐지 만 전체 실행 시간이 2 초 미만이므로 어쨌든 실행 시간을 잘못 계산하여 시간 이동을 설명 할 수 없습니다. 내가 사용한 코드는 다음과 같습니다.
[System.Runtime.InteropServices.DllImport("kernel32")]
extern static UInt64 GetTickCount64();
public static void Main()
{
var start = Stopwatch.StartNew();
var eachStart = Stopwatch.StartNew();
var ticks = Stopwatch.GetTimestamp();
var uptime = ((double)ticks) / Stopwatch.Frequency;
var uptimeTimeSpan = TimeSpan.FromSeconds(uptime);
Console.WriteLine("Stopwatch.GetTimeStamp(): " + uptimeTimeSpan.Subtract(start.Elapsed).ToString(@"dd\d\a\y\s\ hh\h\o\u\r\s\ mm\m\i\n\u\t\e\s\ ss\s\e\c\o\n\d\s"));
Console.WriteLine($"~Time to calculate (ms): {eachStart.Elapsed.TotalMilliseconds}");
eachStart.Restart();
Console.WriteLine("DllImport GetTickCount64(): " + TimeSpan.FromMilliseconds(GetTickCount64()).Subtract(start.Elapsed).ToString(@"dd\d\a\y\s\ hh\h\o\u\r\s\ mm\m\i\n\u\t\e\s\ ss\s\e\c\o\n\d\s"));
Console.WriteLine($"~Time to calculate (ms): {eachStart.Elapsed.TotalMilliseconds}");
eachStart.Restart();
var upTime = new PerformanceCounter("System", "System Up Time");
upTime.NextValue(); //Call this an extra time before reading its value
Console.WriteLine("PerformanceCounter(System, System Up Time): " + TimeSpan.FromSeconds(upTime.NextValue()).Subtract(start.Elapsed).ToString(@"dd\d\a\y\s\ hh\h\o\u\r\s\ mm\m\i\n\u\t\e\s\ ss\s\e\c\o\n\d\s"));
Console.WriteLine($"~Time to calculate (ms): {eachStart.Elapsed.TotalMilliseconds}");
eachStart.Restart();
ManagementObject mo = new ManagementObject(@"\\.\root\cimv2:Win32_OperatingSystem=@");
DateTime lastBootUp = ManagementDateTimeConverter.ToDateTime(mo["LastBootUpTime"].ToString());
Console.WriteLine("ManagementObject LastBootUpTime: " + (DateTime.Now.ToUniversalTime() - lastBootUp.ToUniversalTime()).Subtract(start.Elapsed).ToString(@"dd\d\a\y\s\ hh\h\o\u\r\s\ mm\m\i\n\u\t\e\s\ ss\s\e\c\o\n\d\s"));
Console.WriteLine($"~Time to calculate (ms): {eachStart.Elapsed.TotalMilliseconds}");
}
System.Environment.TickCount
OS 끔찍한 성능 카운터, WMI 또는 기본 호출을 포함하지 않는 정확하고 .
var ticks = Stopwatch.GetTimestamp();
var uptime = ((double)ticks) / Stopwatch.Frequency;
var uptimeSpan = TimeSpan.FromSeconds(uptime);
이를 수행하는 가장 간단하고 적절한 방법은
public static TimeSpan GetUptime()
{
ManagementObject mo = new ManagementObject(@"\\.\root\cimv2:Win32_OperatingSystem=@");
DateTime lastBootUp = ManagementDateTimeConverter.ToDateTime(mo["LastBootUpTime"].ToString());
return DateTime.Now.ToUniversalTime() - lastBootUp.ToUniversalTime();
}
간단하지만 가능합니다.
static DateTime getLastBootTime(ManagementObject mObject)
{
PropertyData pd = mObject.Properties["LastBootUpTime"];
string name = pd.Name.ToString();
DateTime lastBoot = parseCmiDateTime(pd.Value.ToString());
return lastBoot;
}
static ManagementObject getServerOSObject(string serverName)
{
ManagementObjectSearcher mSearcher = new ManagementObjectSearcher("Select * From Win32_OperatingSystem");
mSearcher.Scope = new ManagementScope(String.Format(@"\\{0}\root\cimv2", serverName));
ManagementObjectCollection mObjects = mSearcher.Get();
if (mObjects.Count != 1) throw new Exception(String.Format("Expected 1 object, returned {0}.", mObjects.Count));
foreach (ManagementObject m in mObjects)
{
//No indexing on collection
return m;
}
throw new Exception("Something went wrong!");
}
I know question is both old and solved, but the esiest solution I can tink of is just using the Enviroment.TickCount property, which returns the number of millisecounds since the system started:
System.DateTime SystemStartTime = DateAndTime.Now.AddMilliseconds(-Environment.TickCount);
System.DateTime Uptime = DateAndTime.Now - SystemStartTime;
This solition is a lot faster than the accepted answare.
참고URL : https://stackoverflow.com/questions/972105/retrieve-system-uptime-using-c-sharp
'developer tip' 카테고리의 다른 글
후행 0 유지 (0) | 2020.12.15 |
---|---|
C #에서 디렉터리 찾아보기 (0) | 2020.12.14 |
Google Maps API 3 : 오른쪽 클릭으로 좌표 얻기 (0) | 2020.12.14 |
해시 키 / 값을 배열로 (0) | 2020.12.14 |
Apple Development Push Services의 개인 키를 찾을 수 없습니다. (0) | 2020.12.14 |