gpt4 book ai didi

c# - 在某些地方防止 GC 收集以提高性能

转载 作者:行者123 更新时间:2023-11-30 20:22:27 32 4
gpt4 key购买 nike

我正在运行蒙特卡洛模拟。工作分配给许多不同的机器(通常在 150 台左右)。

每次迭代后,每个工作人员将其结果发送到服务器。在从所有 worker 获得结果后,服务器计算更新并将其发送回所有 worker。

此循环重复 100-1000 次迭代。

服务器在所有工作人员发送结果之前无法计算更新,因此如果 99 个工作人员用 1 秒完成一次迭代,第 100 个工作人员用 10 秒完成,则整个迭代需要 10 秒。

问题是 GC 会在某些迭代中随机启动某些工作人员,从而导致这些工作人员花费更多时间,从而减慢整个过程。

例如,在迭代#1 期间,worker #58 花费了 10 秒,而其他 worker 花费了 8 秒。在第 2 次迭代中,不同的工作人员需要更长的时间,依此类推。

增加的开销似乎在 20-30% 左右。

我想做的是指示 GC 在迭代发生时不要进行任何收集。仅每 10 次迭代收集一次(以便所有工作人员同步他们的收集),或者在发送结果之后以及从服务器获取更新之前收集。

这是我正在尝试做的伪代码:

public void Algorithm()
{
for (var iteration = 0; iteration < 1000; iteration++)
{
PerformIteration(); //don't do any GC inside.
SendResults();
//Now there is a small time window to perform GC
//before results from the server arrive (thats usually sub 0.5sec window)
WaitForUpdate();
}
}

设置:GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency 帮助很大,但仍然存在大量开销。

每个 worker 有 244gb 的 ram,比模拟需要的多得多。此外,几乎所有内容都已缓存,因此无需进行 Gen2 收集。

最佳答案

.NET 4.6 有一个名为 GC.TryStartNoGCRegion 的新 GC 功能.

这告诉 GC 尝试运行这段代码而不进行任何收集:

Attempts to disallow garbage collection during the execution of a critical path if a specified amount of memory is available, and controls whether the garbage collector does a full blocking garbage collection if not enough memory is initially available.

当您调用它时,您指示 GC 在它必须执行 GC 之前可以分配多少内存。它必须小于或等于临时段大小:

public void Algorithm()
{
for (var iteration = 0; iteration < 1000; iteration++)
{
// allow the GC to allocate 4kb
if (GC.TryStartNoGCRegion(4096, true))
{
try
{
PerformIteration();
SendResults();
}
finally
{
GC.EndNoGCRegion();
}
}

//Now there is a small time window to perform GC
//before results from the server arrive (thats usually sub 0.5sec window)
WaitForUpdate();
}
}

关于c# - 在某些地方防止 GC 收集以提高性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31560471/

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