gpt4 book ai didi

Delphi:TTask 仅在第一次时显得很慢

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

单击按钮后,我创建 3 个任务,每个任务都有空过程,并将方法调用和任务列表完成的时间差写入控制台:

procedure TWinTest.BtnThreadTestClick(Sender: TObject);
var
aTasks: array of ITask;
aStart: Cardinal;
begin
aStart := GetTickCount;

Setlength(aTasks, 3);

aTasks[0] := TTask.Create(procedure() begin

end);
aTasks[0].Start;

aTasks[1] := TTask.Create(procedure() begin

end);
aTasks[1].Start;

aTasks[2] := TTask.Create(procedure() begin

end);
aTasks[2].Start;

TTask.WaitForAll(aTasks);


Writeln( GetTickCount - aStart, 'ms');
end;

第一次调用需要 31 毫秒,后续调用需要 0 毫秒。

enter image description here

为什么第一次调用比后续调用慢?也许delphi缓存线程并在后续调用中重用它?

最佳答案

是的,任务线程默认被缓存(在线程池中)。这是有记录的行为:

Tutorial: Using Tasks from the Parallel Programming Library

This tutorial shows how to implement an application using tasks from the Parallel Programming Library (PPL). Tasks are units of work that are in a queue and start when the CPU time is available. Tasks can run operations in parallel. There is a master thread that manages this queue and allocates threads from the thread-pool to do work of the tasks. This thread-pool has a number of threads that depends on the number of CPUs that are available.

您可以通过创建 TThreadPool 来自定义池的行为。对象并将其传递给 TTask构造函数:

If desired, Create can also be given a parameter of TThreadPool from which the instance of TTask may draw the thread resources it needs. Without specifying an instance of TThreadPool, resources are drawn from a default based upon the CPU and threading capabilities of the platform.

关于Delphi:TTask 仅在第一次时显得很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56891154/

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