


What causes Go's 4x performance loss on this array access microbenchmark (relative to GCC)?
In this array access microbenchmark (relative to GCC), Go suffers a 4x performance loss. What causes this? This issue involves many aspects such as the runtime mechanism and compiler optimization of the Go language. First of all, the Go language uses a bounds check mechanism when accessing arrays, that is, bounds checks are performed every time an array element is accessed, which will cause a certain performance loss. Secondly, the Go language compiler is relatively weak in optimization and cannot optimize array access well. In addition, the garbage collection mechanism of the Go language will also have a certain impact on performance. Taken together, these factors combined to cause Go to suffer a 4x performance loss in the array access microbenchmark.
Question content
I wrote this microbenchmark to better understand go's performance characteristics so that I can make informed choices about when to use it.
From a performance overhead perspective, I think this would be the ideal scenario for go:
- No allocation/release inside the loop
- Array access is obviously within bounds (bounds check can be removed)
Nonetheless, I saw a 4x speed difference relative to gcc -o3
on amd64. why is that?
(Use shell timing. It takes a few seconds each time, so startup can be ignored)
package main import "fmt" func main() { fmt.println("started"); var n int32 = 1024 * 32 a := make([]int32, n, n) b := make([]int32, n, n) var it, i, j int32 for i = 0; i < n; i++ { a[i] = i b[i] = -i } var r int32 = 10 var sum int32 = 0 for it = 0; it < r; it++ { for i = 0; i < n; i++ { for j = 0; j < n; j++ { sum += (a[i] + b[j]) * (it + 1) } } } fmt.printf("n = %d, r = %d, sum = %d\n", n, r, sum) }
c Version:
#include <stdio.h> #include <stdlib.h> int main() { printf("started\n"); int32_t n = 1024 * 32; int32_t* a = malloc(sizeof(int32_t) * n); int32_t* b = malloc(sizeof(int32_t) * n); for(int32_t i = 0; i < n; ++i) { a[i] = i; b[i] = -i; } int32_t r = 10; int32_t sum = 0; for(int32_t it = 0; it < r; ++it) { for(int32_t i = 0; i < n; ++i) { for(int32_t j = 0; j < n; ++j) { sum += (a[i] + b[j]) * (it + 1); } } } printf("n = %d, r = %d, sum = %d\n", n, r, sum); free(a); free(b); }
renew:
- Use
range
as recommended to increase go speed by 2 times. - On the other hand,
-march=native
made c 2x faster in my tests. (And-mno-sse
gives a compilation error, apparently incompatible with-o3
) - gccgo looks equivalent to gcc here (and doesn't require
range
)
Solution
Look at the assembler output of the C program and the Go program, at least on the versions of Go and GCC I am using (1.19.6 and 12.2.0 respectively) , the most direct and obvious difference is that GCC automatically vectorizes C programs, while the Go compiler seems unable to do this.
This also nicely explains why you would see a quadruple performance increase, as GCC uses SSE instead of AVX when not targeting a specific architecture, which means the 32-bit scalar instruction width is four times the operating width. In fact, adding -march=native
gave me a 2x performance improvement because it made GCC output AVX code on my CPU.
I'm not familiar enough with Go to tell you whether the Go compiler is intrinsically unable to do autovectorization, or if it's just this particular program that's causing it to error for some reason, but that seems to be the root cause.
The above is the detailed content of What causes Go's 4x performance loss on this array access microbenchmark (relative to GCC)?. For more information, please follow other related articles on the PHP Chinese website!

You should care about the "strings" package in Go because it provides tools for handling text data, splicing from basic strings to advanced regular expression matching. 1) The "strings" package provides efficient string operations, such as Join functions used to splice strings to avoid performance problems. 2) It contains advanced functions, such as the ContainsAny function, to check whether a string contains a specific character set. 3) The Replace function is used to replace substrings in a string, and attention should be paid to the replacement order and case sensitivity. 4) The Split function can split strings according to the separator and is often used for regular expression processing. 5) Performance needs to be considered when using, such as

The"encoding/binary"packageinGoisessentialforhandlingbinarydata,offeringtoolsforreadingandwritingbinarydataefficiently.1)Itsupportsbothlittle-endianandbig-endianbyteorders,crucialforcross-systemcompatibility.2)Thepackageallowsworkingwithcus

Mastering the bytes package in Go can help improve the efficiency and elegance of your code. 1) The bytes package is crucial for parsing binary data, processing network protocols, and memory management. 2) Use bytes.Buffer to gradually build byte slices. 3) The bytes package provides the functions of searching, replacing and segmenting byte slices. 4) The bytes.Reader type is suitable for reading data from byte slices, especially in I/O operations. 5) The bytes package works in collaboration with Go's garbage collector, improving the efficiency of big data processing.

You can use the "strings" package in Go to manipulate strings. 1) Use strings.TrimSpace to remove whitespace characters at both ends of the string. 2) Use strings.Split to split the string into slices according to the specified delimiter. 3) Merge string slices into one string through strings.Join. 4) Use strings.Contains to check whether the string contains a specific substring. 5) Use strings.ReplaceAll to perform global replacement. Pay attention to performance and potential pitfalls when using it.

ThebytespackageinGoishighlyeffectiveforbyteslicemanipulation,offeringfunctionsforsearching,splitting,joining,andbuffering.1)Usebytes.Containstosearchforbytesequences.2)bytes.Splithelpsbreakdownbyteslicesusingdelimiters.3)bytes.Joinreconstructsbytesli

ThealternativestoGo'sbytespackageincludethestringspackage,bufiopackage,andcustomstructs.1)Thestringspackagecanbeusedforbytemanipulationbyconvertingbytestostringsandback.2)Thebufiopackageisidealforhandlinglargestreamsofbytedataefficiently.3)Customstru

The"bytes"packageinGoisessentialforefficientlymanipulatingbyteslices,crucialforbinarydata,networkprotocols,andfileI/O.ItoffersfunctionslikeIndexforsearching,Bufferforhandlinglargedatasets,Readerforsimulatingstreamreading,andJoinforefficient

Go'sstringspackageiscrucialforefficientstringmanipulation,offeringtoolslikestrings.Split(),strings.Join(),strings.ReplaceAll(),andstrings.Contains().1)strings.Split()dividesastringintosubstrings;2)strings.Join()combinesslicesintoastring;3)strings.Rep


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version
SublimeText3 Linux latest version
