- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想制作一些整数大小的 struct
s(即 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;
}
我想测试这个结构的性能。特别是我想看看它是否能让我像使用常规按位算术一样快速地获取单个字节:(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;
}
}
}
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;
编辑:修复代码以确保实际使用了变量。还注释掉了 4 个变量中的 3 个,以真正测试结构转换/成员访问,而不是实际使用变量。
我在 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 |
编辑:修复代码后的新结果:
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 |
基准测试结果让我感到惊讶,这就是为什么我有几个问题:
编辑:更改代码以便实际使用变量后,剩下的问题更少。
System.Runtime.CompilerServices.Unsafe
package (v. 4.5.0) 这么快?我认为它至少会涉及一个方法调用...UInt64
这样的大原始类型。以便我可以更有效地操作/读取该内存?这里的最佳做法是什么?最佳答案
这个问题的答案似乎是,当您使用 Unsafe.As()
时,JIT 编译器可以更好地进行某些优化。 .
Unsafe.As()
像这样非常简单地实现:
public static ref TTo As<TFrom, TTo>(ref TFrom source)
{
return ref source;
}
就是这样!
这是我编写的一个测试程序,用于将其与转换进行比较:
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);
}
}
}
我在我的 PC(x64 发布版本)上得到的结果如下:
ViaStructPointer took 00:00:00.1314279
ViaUnsafeAs took 00:00:00.0249446
如您所见,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;
}
好吧,那里没有什么明显的。但是 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
}
啊哈!这里唯一的区别是:
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
从表面上看,您会期望 conv.u
比用于 Unsafe.As
的两条指令更快.然而,JIT 编译器似乎能够比单个 conv.u
更好地优化这两条指令。 .
问为什么是合理的 - 不幸的是我还没有答案!我几乎可以肯定对 Unsafe::As<>()
的调用正在被JITTER内联,正在被JIT进一步优化。
There is some information about the Unsafe
class' optimisations here.
请注意,为 Unsafe.As<>
生成的 IL就是这样:
.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
}
现在我想,为什么 JITTER 可以将其优化得如此之好变得更加清楚了。
关于c# - 为什么通过 Pointer 转换结构很慢,而 Unsafe.As 很快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50870942/
我有一个 view我拖了一个UITableView在里面,还有 2 UIImageView s(第一个显示背景图像,第二个只是在 View 顶部显示一个非常小的标题和图像)。 它们都设置为 weak特
我尝试用 C# 编写简单的 PostgreSQL 查询。第一个 connection.open() 需要 20 秒。其他连接立即执行。 PGAdmin 工作也很慢。如果我打开“查看所有行”,它也需要大
我制作了一个 html5 视频播放器,我注意到如果当前播放的视频有点大,搜索时间会异常地长。 越接近终点,寻找的时间越长;独立于我之前是否去过那里/与当前时间点的距离有多近,或者我是否缓冲了整个视频。
我正在使用 MaterialDatePicker,但速度很慢。 public class MainActivity extends AppCompatActivity { MaterialDa
我想知道为什么 MyBatis 是 慢 在我的应用程序中。 对于 SELECT COUNT(*) ,所用时间为: 20 秒 - 第一个请求 2-3 秒 - 后续请求 缓存很可能使后续请求更快。 配置
我已经安装了一个默认的开箱即用的 FreeSwitch 实例,但是当我尝试进行内部调用(分机到分机)时,大约需要 12 秒才能建立调用并且我可以听到铃声。 当我查看日志时,我几乎立即看到了连接请求,但
我已经放弃了让它跑得更快的实际尝试。 我最大的问题是,当我插入 html 时,应用程序会变慢到爬行。我有一个进度条,我正在调用 QCoreApplication.processEvents() (顺便
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 9
Doxygen 在我们的代码库上运行大约需要 12 个小时。这主要是因为有很多代码要处理(约 1.5M 行)。然而,它很快就会接近我们无法进行夜间文档更新的地步,因为它们需要太长时间。我们已经不得不减
我正在重写我的旧渲染管道。我根据自己的喜好创建了一个非常精简的原型(prototype),令我震惊的是,我原来相当复杂且优化不佳的管道与 super 简单的原型(prototype)具有完全相同的性能
我想为我的网站使用 Gridster,但我需要使用“add_widget”命令添加很多小部件。我做了一个测试,我认为“add_widget”功能存在问题:网格越来越慢并且存在内存泄漏。 您可以在此视频
我有一份包含图表和表格的报告。 我正在使用 html2canvas与 jsPDF将此报告导出为 PDF 文件。 但是这个过程耗时很长,超过11000ms。 我尝试更改格式和质量,但没有任何效果。 请看
我正在查询大于时间戳的类的所有修订,使用: AuditReaderFactory .get(emf.createEntityManager()) .createQuery().forR
我最近想加速一个加密系统。而在这个系统中,它将使用mysql,因此它包括文件。 而且我发现系统运行缓慢并不是因为加解密,而是因为处理一些sql语句。 它将在运行时使用内存数据库,并使用 中的 mys
谁能看出为什么这需要大约 20 秒?我正在运行下面的代码以将 JSON 请求发布到本地服务器 192.168.1.127。 curl -H "Content-type: application/jso
我有两个表:Posts 和Tags,其中存储了用户发布的文章以及他们为文章附加的标签。 PostTags 表用于表示文章 ID 和标签 ID 的关系。结构如下: 帖子: id | title | au
一个我应该能够自己回答但我没有,而且在谷歌中也找不到任何答案的问题: 我有一个表,其中包含具有以下结构的 500 万行: CREATE TABLE IF NOT EXISTS `files_histo
以下查询在具有大约 50 万行的表上执行需要 20 多秒: SELECT images.id, images.user_id, images_locale.filename, extension, s
我正在使用 $.getJSON 来提取对象 list (100 个项目,不是一个大集合),但 XHR 调用需要 8-10 秒。 想了解我是否缺少某些内容或我可以采取哪些措施来加快我的计划? 最佳答案
在这段代码中,我从网站获取一个字符串并将其显示在标签上。在标签上显示字符串真的很慢!大约 10 秒。但是在控制台 println (date) 上打印字符串时是立即的。我该如何解决这个问题?
我是一名优秀的程序员,十分优秀!