Delphi 2009中的系统正常运行时间

时间:2009-10-29 19:08:22

标签: delphi winapi delphi-2009

如何编码以查看计算机已运行多长时间。

尽可能简单的代码示例。

2 个答案:

答案 0 :(得分:10)

您使用GetTickCount功能,请参阅此示例。

program Ticks;

{$APPTYPE CONSOLE}

uses
  Windows,
  SysUtils;

function TicksToStr(Ticks: Cardinal): string;    //Convert Ticks to String
var
  aDatetime : TDateTime;
begin
   aDatetime := Ticks  / SecsPerDay / MSecsPerSec;
   Result := Format('%d days, %s', [Trunc(aDatetime), FormatDateTime('hh:nn:ss.z', Frac(aDatetime))]) ;
end;

begin
  try
     Writeln('Time Windows was started '+ TicksToStr(GetTickCount));
     Readln;
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;
end.

<强>更新

以其他格式获取信息只需编辑此行,

   Result := Format('%d days, %d hours %d minutes %d seconds ', [Trunc(aDatetime), HourOf(aDatetime),MinuteOf(aDatetime),SecondOf(aDatetime) ]) ;

并添加单位DateUtils。

答案 1 :(得分:5)

请注意,GetTickCount的设计并不是为了准确。

要获得更可靠的时间安排,请使用QueryPerformanceCounterQueryPerformanceFrequency api来电:

function SysUpTime : TDateTime;
var
  Count, Freq : int64;
begin
  QueryPerformanceCounter(count);
  QueryPerformanceFrequency(Freq);
  if (count<> 0) and (Freq <> 0) then
  begin
    Count := Count div Freq;
    Result := Count / SecsPerDay;
  end
  else
    Result := 0;
end;