gpt4 book ai didi

delphi - 如何将毫秒转换为 TDateTime?

转载 作者:行者123 更新时间:2023-12-03 15:03:32 31 4
gpt4 key购买 nike

我正在执行一个长循环,下载数千个文件。我想显示估计的剩余时间,因为这可能需要几个小时。然而,根据我所写的内容,我得到了平均毫秒。如何将此平均下载时间从毫秒转换为 TDateTime

看看我在哪里设置Label1.Caption:

procedure DoWork;
const
AVG_BASE = 20; //recent files to record for average, could be tweaked
var
Avg: TStringList; //for calculating average
X, Y: Integer; //loop iterators
TS, TE: DWORD; //tick counts
A: Integer; //for calculating average
begin
Avg:= TStringList.Create;
try
for X:= 0 to FilesToDownload.Count - 1 do begin //iterate through downloads
if FStopDownload then Break; //for cancelling
if Avg.Count >= AVG_BASE then //if list count is 20
Avg.Delete(0); //remove the oldest average
TS:= GetTickCount; //get time started
try
DownloadTheFile(X); //actual file download process
finally
TE:= GetTickCount - TS; //get time elapsed
end;
Avg.Add(IntToStr(TE)); //add download time to average list
A:= 0; //reset average to 0
for Y:= 0 to Avg.Count - 1 do //iterate through average list
A:= A + StrToIntDef(Avg[Y], 0); //add to total download time
A:= A div Avg.Count; //divide count to get average download time
Label1.Caption:= IntToStr(A); //<-- How to convert to TDateTime?
end;
finally
Avg.Free;
end;
end;

PS - 我愿意采用不同的方法来计算最近 2​​0 次(或 AVG_BASE)下载的平均速度,因为我确信我的字符串列表解决方案不是最好的。我不想根据所有下载来计算它,因为速度可能会随着时间的推移而改变。因此,我只检查最后 20 个。

最佳答案

TDateTime 值本质上是一个 double,其中整数部分是天数,小数部分是时间。

一天有 24*60*60 = 86400 秒(SysUtils 中声明的 SecsPerDay 常量),因此要像 TDateTime 一样获取 A:

dt := A/(SecsPerDay*1000.0); // A is the number of milliseconds 

更好的计时方法是在Diagnostics单元中使用TStopWatch结构。

示例:

sw.Create;
..
sw.Start;
// Do something
sw.Stop;
A := sw.ElapsedMilliSeconds;
// or as RRUZ suggested ts := sw.Elapsed; to get the TimeSpan

要获取平均时间,请考虑使用此移动平均值记录:

Type
TMovingAverage = record
private
FData: array of integer;
FSum: integer;
FCurrentAverage: integer;
FAddIx: integer;
FAddedValues: integer;
public
constructor Create(length: integer);
procedure Add( newValue: integer);
function Average : Integer;
end;

procedure TMovingAverage.Add(newValue: integer);
var i : integer;
begin
FSum := FSum + newValue - FData[FAddIx];
FData[FAddIx] := newValue;
FAddIx := (FAddIx + 1) mod Length(FData);
if (FAddedValues < Length(FData)) then
Inc(FAddedValues);
FCurrentAverage := FSum div FAddedValues;
end;

function TMovingAverage.Average: Integer;
begin
Result := FCurrentAverage;
end;

constructor TMovingAverage.Create(length: integer);
var
i : integer;
begin
SetLength( FData,length);
for i := 0 to length - 1 do
FData[i] := 0;
FSum := 0;
FCurrentAverage := 0;
FAddIx := 0;
FAddedValues := 0;
end;

关于delphi - 如何将毫秒转换为 TDateTime?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12135221/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com