// ----------------------------------------------------------------------------- // file="hlsf-test" // Project: StgSharp // Copyright (c) Nitload. // SPDX-License-Identifier: MIT // ----------------------------------------------------------------------------- using StgSharp.HighPerformance.Memory; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Tlsf = StgSharp.HighPerformance.Memory.TwoLayerSegregatedFitAllocator; namespace StgSharp { internal partial class Program { public static void TestHlsf() { unchecked { nuint size = (nuint)(4UL * 1024UL * 1024UL * 1024UL); // HLSF test arena Console.WriteLine( "=== HLSF (Hybrid Layer Segregated Fit Allocator) Single-threaded Stress Test ===\n"); TwoLayerSegregatedFitAllocator hlsfAllocator = new(size); // === 简洁交替测试:100次alloc与100次free交替进行,直到触发异常或达到最大循环 === Console.WriteLine("\n=== 简洁交替测试:100次alloc + 100次free 交替 ==="); int maxRounds = 10000; // 可调整 int maxCount = 10000; uint[] sizes = [ 64u, 128u, 256u, 512u, 1024u, 4096u, 16384u, 65536u, 262144u, 1048576u ]; int[] offset = [ -4, -3, -2, -1, 0, 1, 2, 3, 4 ]; Random rnd = new Random(42); for (int round = 1; round <= maxRounds; round++) { List batch = new(maxCount); for (int i = 0; i < maxCount; i++) { try { uint sz = sizes[rnd.Next(sizes.Length)]; batch.Add(hlsfAllocator.Alloc(sz)); } catch (Exception e) { Console.WriteLine($"alloced:{round},{i}"); Console.WriteLine(e); throw; } } for (int i = 5; i < maxCount; i += 10) { Tlsf.Handle origin = batch[i]; int index = i + offset[rnd.Next(offset.Length)]; batch[i] = batch[index]; batch[index] = origin; } for (int i = batch.Count - 1; i >= 0; i--) { try { hlsfAllocator.Free(batch[i]); } catch (Exception e) { Console.WriteLine($"freed:{round},{i}"); Console.WriteLine(e); throw; } } if (round % 100 == 0) { Console.WriteLine($"[交替测试] 已完成 {round} 轮 {maxCount}alloc+{maxCount}free"); // hlsfAllocator.DumpPositionChain(false, 10); // hlsfAllocator.Collect(); // hlsfAllocator.DumpPositionChain(false, 10); } } Console.WriteLine("[交替测试] 正常结束,无异常触发"); } } } }