Home > Backend Development > Golang > Why is my Cgo code slower than expected Go code?

Why is my Cgo code slower than expected Go code?

Mary-Kate Olsen
Release: 2024-12-02 09:44:10
Original
333 people have browsed it

Why is my Cgo code slower than expected Go code?

Why is cgo so slow?

Your testing code compares the execution time of C and Go functions run 100 million times each. The C function takes longer than the Golang function, and you are concerned that something is wrong with your testing code.

The high overhead of calling C/C code via CGo makes CGo calls best minimized. In the provided example, it might be more efficient to create a C loop instead of calling a CGo function repeatedly in a loop.

The Go runtime's setup for its threads can break the expectations of C code in several ways:

  1. Relatively small goroutine stacks
  2. Improper interaction with libpthread's thread local storage implementation
  3. Interference with the Go runtime's UNIX signal handler
  4. Potential detriment to other goroutines if C code monopolizes a thread

Therefore, CGo takes the safe approach of running C code in a separate thread with a traditional stack.

Unlike languages like Python where rewriting code hotspots in C was common for speeding up programs, Go's performance gap between C and Go code is much smaller. Consider reserving CGo for interfacing with existing libraries, possibly with small C wrapper functions to reduce the number of calls required from Go.

The above is the detailed content of Why is my Cgo code slower than expected Go code?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template