Home >Backend Development >Golang >Why Is My Cgo Function So Much Slower Than My Equivalent Go Function?
In an attempt to compare the execution times of Cgo and pure Go functions repeatedly, a tester encountered unexpected results. The Cgo function took significantly longer than the Golang function, leading to confusion and an exploration into the testing code.
The provided testing code below compares the execution times for Cgo and pure Go functions, each executed 100 million times:
import ( "fmt" "time" ) /* #include <stdio.h> #include <stdlib.h> #include <string.h> void show() { } */ // #cgo LDFLAGS: -lstdc++ import "C" //import "fmt" func show() { } func main() { now := time.Now() for i := 0; i < 100000000; i = i + 1 { C.show() } end_time := time.Now() var dur_time time.Duration = end_time.Sub(now) var elapsed_min float64 = dur_time.Minutes() var elapsed_sec float64 = dur_time.Seconds() var elapsed_nano int64 = dur_time.Nanoseconds() fmt.Printf("cgo show function elasped %f minutes or \nelapsed %f seconds or \nelapsed %d nanoseconds\n", elapsed_min, elapsed_sec, elapsed_nano) now = time.Now() for i := 0; i < 100000000; i = i + 1 { show() } end_time = time.Now() dur_time = end_time.Sub(now) elapsed_min = dur_time.Minutes() elapsed_sec = dur_time.Seconds() elapsed_nano = dur_time.Nanoseconds() fmt.Printf("go show function elasped %f minutes or \nelapsed %f seconds or \nelapsed %d nanoseconds\n", elapsed_min, elapsed_sec, elapsed_nano) var input string fmt.Scanln(&input) }
The results obtained from the test code showed that invoking the C function was notably slower than the Go function. This led to the question of whether there was any flaw in the testing code itself.
While the provided testing code is valid, the inherent performance limitations of Cgo contribute to the slower execution time observed for the Cgo function.
Calling C/C code through Cgo incurs a relatively high overhead, and minimizing these CGo calls is generally recommended. In this particular scenario, moving the loop down to C instead of repeatedly invoking a CGo function from Go could potentially improve performance.
Additionally, CGo employs a separate thread setup for executing C code, making certain assumptions about the code's behavior. Some of these assumptions can lead to performance impacts:
CGo's role should be primarily seen as a gateway to interfacing with existing libraries, potentially with additional small C wrapper functions to reduce the number of calls made from Go. The expectation of C-like performance optimizations through CGo is generally not met, as there is already less of a performance gap between equivalent C and Go code.
The above is the detailed content of Why Is My Cgo Function So Much Slower Than My Equivalent Go Function?. For more information, please follow other related articles on the PHP Chinese website!