forked from SciSharp/TensorFlow.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStructCastBenchmark.cs
More file actions
72 lines (63 loc) · 1.89 KB
/
Copy pathStructCastBenchmark.cs
File metadata and controls
72 lines (63 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using BenchmarkDotNet.Attributes;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TensorFlowBenchmark.Unmanaged
{
public struct UnmanagedStruct
{
public int a;
public long b;
public UnmanagedStruct(int _)
{
a = 2;
b = 3;
}
}
[SimpleJob(launchCount: 1, warmupCount: 2)]
[MinColumn, MaxColumn, MeanColumn, MedianColumn]
public unsafe class StructCastBenchmark
{
private static void EnsureIsUnmanaged<T>(T _) where T : unmanaged
{ }
static StructCastBenchmark() //if UnmanagedStruct is not unmanaged struct then this will fail to compile.
=> EnsureIsUnmanaged(new UnmanagedStruct());
private IntPtr data;
private void* dataptr;
[GlobalSetup]
public void Setup()
{
data = Marshal.AllocHGlobal(Marshal.SizeOf<UnmanagedStruct>());
dataptr = data.ToPointer();
}
[Benchmark, MethodImpl(MethodImplOptions.NoOptimization)]
public void Marshal_PtrToStructure()
{
UnmanagedStruct _;
for (int i = 0; i < 10000; i++)
{
_ = Marshal.PtrToStructure<UnmanagedStruct>(data);
}
}
[Benchmark, MethodImpl(MethodImplOptions.NoOptimization)]
public void PointerCast()
{
var dptr = dataptr;
UnmanagedStruct _;
for (int i = 0; i < 10000; i++)
{
_ = *(UnmanagedStruct*)dptr;
}
}
[Benchmark, MethodImpl(MethodImplOptions.NoOptimization)]
public void Unsafe_Read()
{
var dptr = dataptr;
UnmanagedStruct _;
for (int i = 0; i < 10000; i++)
{
_ = Unsafe.Read<UnmanagedStruct>(dptr);
}
}
}
}