c# Task.Delay 和 HashedWheelTimer 性能对比
背景
定时或者延时,在游戏中有很广泛的使用。测试一下c#原生的Task.Delay和HashedWheelTimer性能对比
对比结果
其中HashedWheelTimer初始化为
new HashedWheelTimer(tickDuration: TimeSpan.FromMilliseconds(50)
, ticksPerWheel: 100000
, maxPendingTimeouts: 0);
通过对比结果,HashedWheelTimer的cpu占比更低,而且运行更精确
另外,内存消耗其实相差不大,就不贴了
方式 | 任务数量 | 最大超时时间(毫秒) | cpu占比 | 最终消耗时间(毫秒) |
---|---|---|---|---|
Task.Delay | 1000000 | 15000 | 11%-31% | 20332 |
Task.Delay | 2000000 | 15000 | 22%-35% | 30259 |
Task.Delay | 4000000 | 15000 | 25%-35% | 64737 |
WheelTimer | 1000000 | 15000 | 2%-9% | 17325 |
WheelTimer | 2000000 | 15000 | 1%-13% | 18924 |
WheelTimer | 4000000 | 15000 | 1%-15% | 26434 |
测试环境
测试代码
static async void Test15()
{
int taskNum = 1000;
int count = 0;
int maxCount = taskNum;
var wait = new BAwait(-1);
var watch = new Stopwatch();
watch.Start();
for (int i = 0; i < taskNum; ++i)
{
Task.Run(async () =>
{
try
{
int delayCount = 1000;
var tasks = new Task[delayCount];
var curWait = new BAwait(-1);
int curCount = 0;
for (int j = 0; j < delayCount; ++j)
{
tasks[j] = Task.Run(async()=>
{
try
{
//await HashedWheelTimer.INSTANCE.Delay(BRand.Next(500, 15000));
await Task.Delay(BRand.Next(500, 15000));
var value1 = Interlocked.Increment(ref curCount);
if (value1 >= delayCount)
{
curWait.Complete();
}
}
catch (Exception e)
{
Console.WriteLine($"eeeee={e.Message}");
}
});
}
await curWait;
var value = Interlocked.Increment(ref count);
if (value >= maxCount)
{
wait.Complete();
}
}
catch (Exception e)
{
Console.WriteLine($"exception={e.Message}");
}
});
}
await wait;
watch.Stop();
System.GC.Collect();
Console.WriteLine($"finish:count={maxCount},cost={watch.ElapsedMilliseconds}");
}
版权声明:本文为bestans原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。