using BenchmarkDotNet.Running; using BenchmarkDotNet.Attributes; using System.Runtime.InteropServices; using System.Reflection; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.Versioning; namespace BenchMark { internal class Program { static unsafe void Main(string[] args) { int* p = (int*)Marshal.AllocHGlobal(sizeof(int) * 10); for (int i = 0; i < 10; i++) { *(p + i) = i; } int[] array = (int[])GCHandle.FromIntPtr((IntPtr)p).Target; Console.WriteLine(array); //BenchmarkRunner.Run(typeof(MyClass).Assembly); } } public class MyClass { [Benchmark] public bool isM128Pinnable() { var type = typeof(M128); foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { // 如果字段是引用类型,返回 false if (!field.FieldType.IsValueType) { return false; } } // 如果没有引用类型的字段,返回 true return true; } [Benchmark] public bool isVector4Pinnable() { var type = typeof(int); foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { // 如果字段是引用类型,返回 false if (!field.FieldType.IsValueType) { return false; } } // 如果没有引用类型的字段,返回 true return true; } } [StructLayout(LayoutKind.Explicit)] public unsafe struct M128 { [FieldOffset(0)] internal fixed float Single[4]; [FieldOffset(0)] internal fixed double Double[2]; [FieldOffset(0)] internal fixed sbyte Int8[16]; [FieldOffset(0)] internal fixed short Int16[8]; [FieldOffset(0)] internal fixed int Int32[4]; [FieldOffset(0)] internal fixed long Int64[2]; [FieldOffset(0)] internal fixed byte UInt8[16]; [FieldOffset(0)] internal fixed ushort UInt16[8]; [FieldOffset(0)] internal fixed uint UInt32[4]; [FieldOffset(0)] internal fixed ulong UInt64[2]; } }