gpt4 book ai didi

Delphi TParallel.For 比经典 for 慢

转载 作者:行者123 更新时间:2023-12-03 18:59:45 25 4
gpt4 key购买 nike

我需要填充 TJsonArray有很多TJsonObject ( TJsonArrayTJsonObject 来自 JsonDataObjects )。我正在尝试 TParallel.For()来自 System.Threading单位来提高性能,但我的TParallel.For()比经典的 for 慢环形。

这是我的测试代码:

var
aLock: TCriticalSection;
jItems: TJsonArray;
jItem: TJsonObject;
aStart: Cardinal;
aEnd: Cardinal;
i: integer;
begin
// array of json objects
jItems := TJsonArray.Create;

// ASYNC FOR LOOP
// ----------------------------
aLock := TCriticalSection.Create;
aStart := GetTickCount;
TParallel.&For(0, 10000000,
procedure(k: Integer)
var
xItem: TJsonObject;
begin
aLock.Enter;
try
// add new object to the array
xItem := jItems.AddObject;
finally
aLock.Leave;
end;
// populate some object property for test
xItem.I['I'] := k; // .I for integer
xItem.F['F'] := k; // .F for float
xItem.S['S'] := IntToStr(k); // .S for string
xItem.D['D'] := Now; // .D for date
end
);
aEnd := GetTickCount;
Writeln('ASYNC ', aEnd-aStart);
// ----------------------------

aLock.Free;
jItems.Clear;

// SYNC FOR LOOP
// ----------------------------
aStart := GetTickCount;
for i := 0 to 10000000 do begin
jItem := jItems.AddObject;
jItem.I['I'] := i;
jItem.F['F'] := i;
jItem.S['S'] := IntToStr(i);
jItem.D['D'] := Now;
end;
aEnd := GetTickCount;
Writeln('SYNC ', aEnd-aStart);
// ----------------------------

jItems.Free;
end;

这是结果(数字是耗时,以毫秒为单位):

image

我想我的 TParallel.For()执行是错误的。我究竟做错了什么?

最佳答案

正如其他人所提到的,您使用 TJsonArray 周围的关键部分序列化你的线程并且可能是一个主要的瓶颈。尝试摆脱临界区,在进入循环之前预先分配数组,然后让每个循环迭代根据需要简单地填充数组的现有槽。这样,您就有更好的机会将多个对象同时并行插入到数组中。

var
jItems: TJsonArray;
jItem: TJsonObject;
aStart: Cardinal;
aEnd: Cardinal;
i: integer;
begin
// array of json objects
jItems := TJsonArray.Create;

// ASYNC FOR LOOP
// ----------------------------
jItems.Count := 10000001; // <-- add this!
aStart := GetTickCount;
TParallel.&For(0, 10000000,
procedure(k: Integer)
var
xItem: TJsonObject;
begin

// create new object
xItem := TJsonObject.Create;

// populate some object property for test
xItem.I['I'] := k; // .I for integer
xItem.F['F'] := k; // .F for float
xItem.S['S'] := IntToStr(k); // .S for string
xItem.D['D'] := Now; // .D for date

// add new object to the array
jItems.O[k] := xItem;
end
);
aEnd := GetTickCount;
Writeln('ASYNC ', aEnd-aStart);
// ----------------------------

jItems.Clear;

// SYNC FOR LOOP
// ----------------------------
aStart := GetTickCount;
for i := 0 to 10000000 do begin
jItem := jItems.AddObject;
jItem.I['I'] := i;
jItem.F['F'] := i;
jItem.S['S'] := IntToStr(i);
jItem.D['D'] := Now;
end;
aEnd := GetTickCount;
Writeln('SYNC ', aEnd-aStart);
// ----------------------------

jItems.Free;
end;

关于Delphi TParallel.For 比经典 for 慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57113709/

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