tags:

views:

290

answers:

2

How can I code to see how long the computer has been on.

Simple examples of code if possible.

+10  A: 

You use GetTickCount function see this example.

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.

UPDATE

to get the info in other format just must edit this line,

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

and add the unit DateUtils.

RRUZ
Thats good for when, but I need how long like 4 days 3 hours 2 mins u see what i mean
Jim Moore
Not that I know Delphi, but it looks like he has that there.
jprete
@Jim: Days followed by hh:mm:ss.z is clearly what you want.
Jeroen Pluimers
@RE Its a very good, detailed answer, and I don't need to run that through the compiler to see its perfect. He has answered your question in full, so I would suggest you accept it.
Reallyethical
Thank you that works well now.
Jim Moore
GetTickCount will wrap around to zero after ~49.7 days. Better use the performance counter 'System Up Time' or, on Vista and later versions, GetTickCount64.
TOndrej
+3  A: 

Note that GetTickCount isn't really designed for accuracy.

For more reliable timing, use the QueryPerformanceCounter and QueryPerformanceFrequency api calls:

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;
Gerry
Exactly how "accurate" do you require your uptime measurement to be?!?
Craig Stuntz
Not much really - depend on what he wants to use it for. I seem to recall someone saying that GetTickCount may miss some millseconds, but I have no evidence of that - in retrospect, I suspect it was nonsense.
Gerry