绝对最快(和希望优雅)的方式返回一个给定结构类型的某个char缓冲区 [英] Absolute fastest (and hopefully elegant) way to return a certain char buffer given a struct type

查看:156
本文介绍了绝对最快(和希望优雅)的方式返回一个给定结构类型的某个char缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定首先,最重要的是,性能在这里是最重要的,所以我怀疑地图将工作。我有一个结构列表(约16个),如

OK first and foremost, performance is most important here so I doubt a map would work. I have a list of structs (about 16 of them) like

struct A { ... };
struct B { ... }; 
...

各不相同,每个大小不同。

each are different and each are of different sizes.

我想知道我们可以用什么优雅的方式来做一些符合以下行为的事情:

I'm wondering what elegant way we might be able to do something along the lines of:

char BufferA[sizeof(struct A)];
char BufferB[sizeof(struct B)];

然后写一些方法或映射返回BufferA,如果你正在使用结构A.速度绝对是最重要的是,我想象使用模板会有所帮助,但我不确定整个事情可以模板化。

then write some method or mapping to return BufferA if you are working with struct A. Speed is definitely the most important, I imagine using templates would help but I'm not sure it the whole thing can be templatized.

更新***对不起,都是预分配的。我只需要一个非常快速的方法来获得正确的缓冲区给定一个结构类型。

Update*** Sorry for not being clear, the buffers are all pre-allocated. I just need a very fast way to get the proper Buffer given a struct type.

更新2 ***对不起指定,对齐是一个重要的特质在这里和我实际上用#pragma pack(push,1)将每个结构字节对齐

Update 2*** Sorry for not specifying, alignment is an important trait here and I do in fact byte-align each struct with #pragma pack(push, 1)

推荐答案

template<typename X>
struct Buffer
{
    static char *ptr()
    {
        // Note if no alignment is needed for your use then
        // just a simple "static char buf[sizeof(X)]; return buf;"
        // would be sufficient instead of the following.
        union Aligner {
            X x;
            char buf[sizeof(X)];
        };

        static Aligner a;

        return a.buf;
    }
};

struct B
{
    int x, y, z;
};

void foo()
{
    Buffer<B>::ptr()[2] = 12;
}

使用 g ++ -O2 上面的代码仅在 foo 中产生固定的内存写入操作。

With g++ -O2 the code above generates just a fixed memory write operation in foo.

.globl _Z3foov
    .type   _Z3foov, @function
_Z3foov:
.LFB1:
    .cfi_startproc
    .cfi_personality 0x0,__gxx_personality_v0
    pushl   %ebp
    .cfi_def_cfa_offset 8
    movl    %esp, %ebp
    .cfi_offset 5, -8
    .cfi_def_cfa_register 5

    movb    $12, _ZZN6BufferI1BE3ptrEvE1a+2   <=== this is the assignment

    popl    %ebp
    ret
    .cfi_endproc

这篇关于绝对最快(和希望优雅)的方式返回一个给定结构类型的某个char缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆