是否可以在单个命令中存储8个字节

Is it possible to store 8 bytes in single command

本文关键字:存储 8个 字节 命令 单个 是否      更新时间:2023-10-16

我正在写一个实时代码,所以时间很重要

我使用C++英特尔本能

我想知道是否可以在一个命令中存储8个无符号字符(8个字节(,而不是使用循环?

char* buff = foo(); 
for (auto i = 0; i < 8; i++) 
{
    buff[i] = 0x00; 
}

正在寻找类似的东西

_mm256_store_ps(...)

我想过这样做,但这不起作用(我不知道为什么(

_int64* buff = foo(); 
*buff = 0x00000000; 

有关于更快代码的建议吗?

让编译器担心最好的方法:

memset(buff, 0, 8);

当然,如果这真的很关键,那么看看它生成的代码。

您不需要内在指令,因为普通整数指令是以8位、16位、32位或64位增量存储零的最有效方法。

char* buff = foo();
*((uint64_t*)buff) = 0;

由于char*可以别名任何东西,因此这是安全的。但如果buff有不同的类型,如short *,则不安全。

优化时,始终从查看编译器的功能开始。

#include <string.h>
#include <cstdint>
extern char* foo();
char* f1() {
  char* buf = foo();
  for (auto i = 0; i < 8; ++i)
    buf[i] = 0;
  return buf;
}
char* f2() {
  char* buf = foo();
  memset(buf, 0, 8);
  return buf;
}
char* f3() {
  char* buf = foo();
  *((uint64_t*)buf) = 0ULL;
  return buf;
}

用带有-O3的GCC编译,上面每一个的输出都是用于存储0s的单个指令:

godbolt 演示

f1():
        subq    $8, %rsp
        call    foo()
        movq    $0, (%rax)  ; << Here
        addq    $8, %rsp
        ret
f2():
        subq    $8, %rsp
        call    foo()
        movq    $0, (%rax)  ; << Here
        addq    $8, %rsp
        ret
f3():
        subq    $8, %rsp
        call    foo()
        movq    $0, (%rax)  ; << Here
        addq    $8, %rsp
        ret