Fit*_*Dev 8 c# performance struct unsafe c#-7.2
我想使几个整数大小structS(即32个64位)是从原始非托管类型具有相同的尺寸能容易转变为/(即Int32与UInt32用于特别是32位大小的结构).
然后,结构将公开用于位操作/索引的附加功能,这些功能不能直接在整数类型上使用.基本上,作为一种语法糖,提高可读性和易用性.
然而,重要的部分是性能,因为这个额外的抽象应该基本上是0成本(在一天结束时,CPU应该"看到"相同的位,就好像处理原始的整数一样).
以下是struct我提出的最基本的内容.它没有所有功能,但足以说明我的问题:
[StructLayout(LayoutKind.Explicit, Pack = 1, Size = 4)]
public struct Mask32 {
[FieldOffset(3)]
public byte Byte1;
[FieldOffset(2)]
public ushort UShort1;
[FieldOffset(2)]
public byte Byte2;
[FieldOffset(1)]
public byte Byte3;
[FieldOffset(0)]
public ushort UShort2;
[FieldOffset(0)]
public byte Byte4;
[DebuggerStepThrough, MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe implicit operator Mask32(int i) => *(Mask32*)&i;
[DebuggerStepThrough, MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe implicit operator Mask32(uint i) => *(Mask32*)&i;
}
Run Code Online (Sandbox Code Playgroud)
我想测试这个结构的性能.特别是我想知道如果我使用常规的逐位算术,它是否可以让我快速获得单个字节 :( (i >> 8) & 0xFF例如,获取第3个字节).
下面你会看到我提出的基准:
public unsafe class MyBenchmark {
const int count = 50000;
[Benchmark(Baseline = true)]
public static void Direct() {
var j = 0;
for (int i = 0; i < count; i++) {
//var b1 = i.Byte1();
//var b2 = i.Byte2();
var b3 = i.Byte3();
//var b4 = i.Byte4();
j += b3;
}
}
[Benchmark]
public static void ViaStructPointer() {
var j = 0;
int i = 0;
var s = (Mask32*)&i;
for (; i < count; i++) {
//var b1 = s->Byte1;
//var b2 = s->Byte2;
var b3 = s->Byte3;
//var b4 = s->Byte4;
j += b3;
}
}
[Benchmark]
public static void ViaStructPointer2() {
var j = 0;
int i = 0;
for (; i < count; i++) {
var s = *(Mask32*)&i;
//var b1 = s.Byte1;
//var b2 = s.Byte2;
var b3 = s.Byte3;
//var b4 = s.Byte4;
j += b3;
}
}
[Benchmark]
public static void ViaStructCast() {
var j = 0;
for (int i = 0; i < count; i++) {
Mask32 m = i;
//var b1 = m.Byte1;
//var b2 = m.Byte2;
var b3 = m.Byte3;
//var b4 = m.Byte4;
j += b3;
}
}
[Benchmark]
public static void ViaUnsafeAs() {
var j = 0;
for (int i = 0; i < count; i++) {
var m = Unsafe.As<int, Mask32>(ref i);
//var b1 = m.Byte1;
//var b2 = m.Byte2;
var b3 = m.Byte3;
//var b4 = m.Byte4;
j += b3;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在Byte1(),Byte2(),Byte3(),和Byte4()是正义的扩展方法确实会内联,只是做位运算和铸造获得的第n个字节:
[DebuggerStepThrough, MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte Byte1(this int it) => (byte)(it >> 24);
[DebuggerStepThrough, MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte Byte2(this int it) => (byte)((it >> 16) & 0xFF);
[DebuggerStepThrough, MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte Byte3(this int it) => (byte)((it >> 8) & 0xFF);
[DebuggerStepThrough, MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte Byte4(this int it) => (byte)it;
Run Code Online (Sandbox Code Playgroud)
编辑:修复了确保变量实际使用的代码.还注释了4个变量中的3个来真正测试结构转换/成员访问而不是实际使用变量.
我在Release版本中运行了这些,并在x64上进行了优化.
Intel Core i7-3770K CPU 3.50GHz (Ivy Bridge), 1 CPU, 8 logical cores and 4 physical cores
Frequency=3410223 Hz, Resolution=293.2360 ns, Timer=TSC
[Host] : .NET Framework 4.6.1 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.6.1086.0
DefaultJob : .NET Framework 4.6.1 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.6.1086.0
Method | Mean | Error | StdDev | Scaled | ScaledSD |
------------------ |----------:|----------:|----------:|-------:|---------:|
Direct | 14.47 us | 0.3314 us | 0.2938 us | 1.00 | 0.00 |
ViaStructPointer | 111.32 us | 0.6481 us | 0.6062 us | 7.70 | 0.15 |
ViaStructPointer2 | 102.31 us | 0.7632 us | 0.7139 us | 7.07 | 0.14 |
ViaStructCast | 29.00 us | 0.3159 us | 0.2800 us | 2.01 | 0.04 |
ViaUnsafeAs | 14.32 us | 0.0955 us | 0.0894 us | 0.99 | 0.02 |
Run Code Online (Sandbox Code Playgroud)
编辑:修复代码后的新结果:
Method | Mean | Error | StdDev | Scaled | ScaledSD |
------------------ |----------:|----------:|----------:|-------:|---------:|
Direct | 57.51 us | 1.1070 us | 1.0355 us | 1.00 | 0.00 |
ViaStructPointer | 203.20 us | 3.9830 us | 3.5308 us | 3.53 | 0.08 |
ViaStructPointer2 | 198.08 us | 1.8411 us | 1.6321 us | 3.45 | 0.06 |
ViaStructCast | 79.68 us | 1.5478 us | 1.7824 us | 1.39 | 0.04 |
ViaUnsafeAs | 57.01 us | 0.8266 us | 0.6902 us | 0.99 | 0.02 |
Run Code Online (Sandbox Code Playgroud)
基准测试结果让我感到惊讶,这就是为什么我有几个问题:
编辑:更改代码后仍然存在较少的问题,以便实际使用变量.
System.Runtime.CompilerServices.Unsafe包装(v.4.5.0)如此之快?我认为它至少会涉及一个方法调用...UInt64以便我可以更有效地操作/读取该内存?这里的最佳做法是什么?当您获取本地地址时,jit 通常必须将该本地地址保留在堆栈中。这里就是这种情况。在ViaPointer版本i中保存在堆栈上。在ViaUnsafe,i被复制到一个临时和临时保存在堆栈中。前者较慢,因为i也用于控制循环的迭代。
您可以ViaUnsafe使用以下代码非常接近性能,您可以在其中明确复制:
public static int ViaStructPointer2()
{
int total = 0;
for (int i = 0; i < count; i++)
{
int j = i;
var s = (Mask32*)&j;
total += s->Byte1;
}
return total;
}
ViaStructPointer took 00:00:00.1147793
ViaUnsafeAs took 00:00:00.0282828
ViaStructPointer2 took 00:00:00.0257589
Run Code Online (Sandbox Code Playgroud)
答案似乎是JIT编译器在您使用时可以更好地进行某些优化Unsafe.As().
Unsafe.As() 实现非常简单:
public static ref TTo As<TFrom, TTo>(ref TFrom source)
{
return ref source;
}
Run Code Online (Sandbox Code Playgroud)
而已!
这是我写的一个测试程序,用于比较铸造:
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Demo
{
[StructLayout(LayoutKind.Explicit, Pack = 1, Size = 4)]
public struct Mask32
{
[FieldOffset(3)]
public byte Byte1;
[FieldOffset(2)]
public ushort UShort1;
[FieldOffset(2)]
public byte Byte2;
[FieldOffset(1)]
public byte Byte3;
[FieldOffset(0)]
public ushort UShort2;
[FieldOffset(0)]
public byte Byte4;
}
public static unsafe class Program
{
static int count = 50000000;
public static int ViaStructPointer()
{
int total = 0;
for (int i = 0; i < count; i++)
{
var s = (Mask32*)&i;
total += s->Byte1;
}
return total;
}
public static int ViaUnsafeAs()
{
int total = 0;
for (int i = 0; i < count; i++)
{
var m = Unsafe.As<int, Mask32>(ref i);
total += m.Byte1;
}
return total;
}
public static void Main(string[] args)
{
var sw = new Stopwatch();
sw.Restart();
ViaStructPointer();
Console.WriteLine("ViaStructPointer took " + sw.Elapsed);
sw.Restart();
ViaUnsafeAs();
Console.WriteLine("ViaUnsafeAs took " + sw.Elapsed);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我在PC上获得的结果(x64版本构建)如下:
ViaStructPointer took 00:00:00.1314279
ViaUnsafeAs took 00:00:00.0249446
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,ViaUnsafeAs确实要快得多.
那么让我们看一下编译器生成的内容:
public static unsafe int ViaStructPointer()
{
int total = 0;
for (int i = 0; i < Program.count; i++)
{
total += (*(Mask32*)(&i)).Byte1;
}
return total;
}
public static int ViaUnsafeAs()
{
int total = 0;
for (int i = 0; i < Program.count; i++)
{
total += (Unsafe.As<int, Mask32>(ref i)).Byte1;
}
return total;
}
Run Code Online (Sandbox Code Playgroud)
好的,那里没有什么明显的.但是IL怎么样?
.method public hidebysig static int32 ViaStructPointer () cil managed
{
.locals init (
[0] int32 total,
[1] int32 i,
[2] valuetype Demo.Mask32* s
)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: br.s IL_0017
.loop
{
IL_0006: ldloca.s i
IL_0008: conv.u
IL_0009: stloc.2
IL_000a: ldloc.0
IL_000b: ldloc.2
IL_000c: ldfld uint8 Demo.Mask32::Byte1
IL_0011: add
IL_0012: stloc.0
IL_0013: ldloc.1
IL_0014: ldc.i4.1
IL_0015: add
IL_0016: stloc.1
IL_0017: ldloc.1
IL_0018: ldsfld int32 Demo.Program::count
IL_001d: blt.s IL_0006
}
IL_001f: ldloc.0
IL_0020: ret
}
.method public hidebysig static int32 ViaUnsafeAs () cil managed
{
.locals init (
[0] int32 total,
[1] int32 i,
[2] valuetype Demo.Mask32 m
)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: br.s IL_0020
.loop
{
IL_0006: ldloca.s i
IL_0008: call valuetype Demo.Mask32& [System.Runtime.CompilerServices.Unsafe]System.Runtime.CompilerServices.Unsafe::As<int32, valuetype Demo.Mask32>(!!0&)
IL_000d: ldobj Demo.Mask32
IL_0012: stloc.2
IL_0013: ldloc.0
IL_0014: ldloc.2
IL_0015: ldfld uint8 Demo.Mask32::Byte1
IL_001a: add
IL_001b: stloc.0
IL_001c: ldloc.1
IL_001d: ldc.i4.1
IL_001e: add
IL_001f: stloc.1
IL_0020: ldloc.1
IL_0021: ldsfld int32 Demo.Program::count
IL_0026: blt.s IL_0006
}
IL_0028: ldloc.0
IL_0029: ret
}
Run Code Online (Sandbox Code Playgroud)
啊哈!这里唯一的区别是:
ViaStructPointer: conv.u
ViaUnsafeAs: call valuetype Demo.Mask32& [System.Runtime.CompilerServices.Unsafe]System.Runtime.CompilerServices.Unsafe::As<int32, valuetype Demo.Mask32>(!!0&)
ldobj Demo.Mask32
Run Code Online (Sandbox Code Playgroud)
从表面上看,你会期望conv.u比用于的两条指令更快Unsafe.As.但是,似乎JIT编译器能够比单个指令更好地优化这两个指令conv.u.
有理由问为什么会这样 - 很遗憾我还没有答案!我几乎可以肯定,Unsafe::As<>()JITTER正在调用它,JIT正在进一步优化它.
请注意,生成的IL Unsafe.As<>只是这样:
.method public hidebysig static !!TTo& As<TFrom, TTo> (
!!TFrom& source
) cil managed aggressiveinlining
{
.custom instance void System.Runtime.Versioning.NonVersionableAttribute::.ctor() = (
01 00 00 00
)
IL_0000: ldarg.0
IL_0001: ret
}
Run Code Online (Sandbox Code Playgroud)
现在我认为为什么JITTER能够如此好地优化它变得更加清晰.