dqstti8945 2017-11-19 04:20
浏览 102

Go中的地址对齐

So I am using c2go to link C code with Go. The C code requires certain arguments of a function called from Go to be 256 bit aligned (the function arguments are all pointers to Go variables). Is there a way to achieve this is Go (i.e. to specify 256 alignment for a variable in Go)?

In Go, "unsafe.Alignof(f)" shows as 8 bytes aligned (for "var f [8]float32") i.e. the f is guaranteed by Go to be only 8 bytes aligned. I need it to be 32 bytes aligned somehow.

For the curious: The C code is using SIMD instructions (AVX to be specific). I was using "vmovaps" instruction which requires 256 bit alignment of operands. I can get away with using "vmovups" which doesn't require alignment, but I suspect that has a performance penalty.

  • 写回答

2条回答 默认 最新

  • 普通网友 2017-11-19 06:26
    关注

    For example, trading more memory for less CPU time,

    package main
    
    import (
        "fmt"
        "unsafe"
    )
    
    // Float32Align32 returns make([]float32, n) 32-byte aligned.
    func Float32Align32(n int) []float32 {
        // align >= size && align%size == 0
        const align = 32 // SIMD AVX byte alignment
        const size = unsafe.Sizeof(float32(0))
        const pad = int(align/size - 1)
        if n <= 0 {
            return nil
        }
        s := make([]float32, n+pad)
        p := uintptr(unsafe.Pointer(&s[0]))
        i := int(((p+align-1)/align*align - p) / size)
        j := i + n
        return s[i:j:j]
    }
    
    func main() {
        f := Float32Align32(8) // SIMD AVX
        fmt.Printf(
            "SIMD AVX: %T %d %d %p %g
    ",
            f, len(f), cap(f), &f[0], f,
        )
        CFuncArg := &f[0]
        fmt.Println("CFuncArg:", CFuncArg)
    }
    

    Playground: https://play.golang.org/p/mmFnHEwGKt

    Output:

    SIMD AVX: []float32 8 8 0x10436080 [0 0 0 0 0 0 0 0]
    CFuncArg: 0x10436080
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器