From 3fb8e60a1dd3709238a920800a539957179180d7 Mon Sep 17 00:00:00 2001 From: Jille Timmermans Date: Fri, 12 Jul 2024 19:59:46 +0200 Subject: [PATCH] Check if the current CPU has AVX2 support If built with GOAMD64=v3+ we know it is and resolve it compile time --- detect_axv2_always.go | 7 +++++++ detect_axv2_never.go | 7 +++++++ detect_axv2_runtime.go | 9 +++++++++ go.mod | 2 ++ go.sum | 2 ++ lib.go | 6 +++++- 6 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 detect_axv2_always.go create mode 100644 detect_axv2_never.go create mode 100644 detect_axv2_runtime.go diff --git a/detect_axv2_always.go b/detect_axv2_always.go new file mode 100644 index 0000000..3b63bd8 --- /dev/null +++ b/detect_axv2_always.go @@ -0,0 +1,7 @@ +//go:build amd64.v3 + +package and + +func hasAVX2() bool { + return true +} diff --git a/detect_axv2_never.go b/detect_axv2_never.go new file mode 100644 index 0000000..5f3cef5 --- /dev/null +++ b/detect_axv2_never.go @@ -0,0 +1,7 @@ +//go:build !amd64 + +package and + +func hasAVX2() bool { + return false +} diff --git a/detect_axv2_runtime.go b/detect_axv2_runtime.go new file mode 100644 index 0000000..5850d8d --- /dev/null +++ b/detect_axv2_runtime.go @@ -0,0 +1,9 @@ +//go:build amd64 && !amd64.v3 + +package and + +import "golang.org/x/sys/cpu" + +func hasAVX2() bool { + return cpu.X86.HasAVX2 +} diff --git a/go.mod b/go.mod index 4eb648e..ac4ad79 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module github.com/bwesterb/go-and go 1.22.0 + +require golang.org/x/sys v0.22.0 diff --git a/go.sum b/go.sum index e69de29..96f003d 100644 --- a/go.sum +++ b/go.sum @@ -0,0 +1,2 @@ +golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI= +golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= diff --git a/lib.go b/lib.go index 1b608fd..9e71a3f 100644 --- a/lib.go +++ b/lib.go @@ -13,7 +13,11 @@ func And(dst, a, b []byte) { panic("lengths of a, b and dst must be equal") } - and(dst, a, b) + if hasAVX2() { + and(dst, a, b) + return + } + andGeneric(dst, a, b) } func andGeneric(dst, a, b []byte) {