search
HomeBackend DevelopmentGolangBenchmark with Golang

Hello Gophers ?

In this blog post, I will show you how to use an awesome tool built into the #golang testing package. How would you test the performance of a piece of code or a function? Use benchmark tests.

Let’s go.

For this test, I'll be using the classic Fibonacci Number or Fibonacci Sequence, which is determined by:

if (x 



<p>This sequence is important because it appears in several parts of mathematics and nature as well, as shown below:</p>

<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172554306490300.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Benchmark with Golang"></p>

<p>There are several ways to implement this code, and I'll be picking two for our benchmark testing: the recursive and iterative methods of calculating it. The main objective of the functions is to provide a <em>position</em> and return the Fibonacci number at that position.</p>

<h2>
  
  
  Recursive Method
</h2>



<pre class="brush:php;toolbar:false">// main.go

func fibRecursive(n int) int {
    if n 



<h2>
  
  
  Iterative Method
</h2>



<pre class="brush:php;toolbar:false">// main.go

func fibIterative(position uint) uint {
    slc := make([]uint, position)
    slc[0] = 1
    slc[1] = 1

    if position 



<p>These methods are not optimized, but the results of the tests are significantly different even for a small number. You'll see this in the tests. To follow along with the code, you can click here.</p>

<p>Now, for the <strong>benchmark</strong> tests, let’s write some tests in the _main_test.go file. Using Golang's documentation on <strong>benchmark</strong>, you can create the functions to be tested as follows:<br>
</p>

<pre class="brush:php;toolbar:false">// main_test.go

// The key is to start every function you want to benchmark with the keyword Benchmark and use b *testing.B instead of t *testing.T as input 
func BenchmarkFibIterative(b *testing.B) {
    // Use this for-loop to ensure the code will behave correctly. 
    // Now, you can put the function or piece of code you want to test
    for i := 0; i 



<blockquote>
<p>Question, before you go on: which one is faster?</p>
</blockquote>

<p>Let's run the test for a small number (10) and for a slightly bigger number (80). To run the <strong>benchmark</strong> tests, you simply run the command:</p>

<p>go test -bench=NameoftheFunction</p>

<p>If you want to know more about this command, check here.</p>

<p><strong>First test: position=10</strong><br>
</p>

<pre class="brush:php;toolbar:false">//(fibIterative)
Results:
cpu: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
BenchmarkFibIterative-8         24491042                42.50 ns/op
PASS
ok      playground      1.651s

Let’s analyze with the help of this image:

Benchmark with Golang

According to the image, we have 8 cores for the tests, no time limit (it will run until completion). It took 1.651s to complete the task.

==== Extra ====
We got 24,491,042 iterations (computations), and each iteration (op) took 42.50 ns.

Doing some math, we can calculate how much time one op took:

42.50 ns/op with 1 ns = 1/1,000,000,000 s
op ≈ 2.35270590588e-12 s
==== Extra ====

That’s a good result. Let’s check the recursive function for position 10:

// Results
BenchmarkFibRecursive-8          6035011               187.8 ns/op
PASS
ok      playground      1.882s

We can see that it took 1.882s to complete the task.

The iterative function won by a few deciseconds. Let’s try one more test with:

Position 50

// Results for the Iterative Function

cpu: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
BenchmarkFibIterative-8         27896118                45.37 ns/op
PASS
ok      playground      2.876s

// Results for the Recursive Function

cpu: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
BenchmarkFibRecursive-8          6365198               186.3 ns/op
PASS
ok      playground      1.918s

Wow! Now the recursive function is faster?

Let’s finish with a slightly larger number.

Position 80

// Results for the Iterative Function

cpu: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
BenchmarkFibIterative-8          5102344               229.5 ns/op
PASS
ok      playground      1.933s

// Results for the Recursive Function
// My poor PC couldn’t handle it, so I had to reduce the position to 50 just to get some results printed.

cpu: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
BenchmarkFibRecursive-8                1        44319299474 ns/op
PASS
ok      playground      44.951s

The difference is huge. For position 80, the iterative approach took approximately 2 seconds. For position 50, the recursive function took around 45 seconds. This demonstrates the importance of benchmarking your code when your Golang project starts to slow down.

Conclusion

If your production code is running slowly or is unpredictably slower, you can use this technique, combined with pprof or other tools from the built-in testing package, to identify and test where your code is performing poorly and how to optimize it.

Side note: not all code that is beautiful to the eyes is more performant.

Extra Exercise

Can you find a better way to improve the recursive function? (Tip: use Dynamic Programming). This article explains why for some small numbers, the recursive strategy is better.

The above is the detailed content of Benchmark with Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Testing Code that Relies on init Functions in GoTesting Code that Relies on init Functions in GoMay 03, 2025 am 12:20 AM

WhentestingGocodewithinitfunctions,useexplicitsetupfunctionsorseparatetestfilestoavoiddependencyoninitfunctionsideeffects.1)Useexplicitsetupfunctionstocontrolglobalvariableinitialization.2)Createseparatetestfilestobypassinitfunctionsandsetupthetesten

Comparing Go's Error Handling Approach to Other LanguagesComparing Go's Error Handling Approach to Other LanguagesMay 03, 2025 am 12:20 AM

Go'serrorhandlingreturnserrorsasvalues,unlikeJavaandPythonwhichuseexceptions.1)Go'smethodensuresexpliciterrorhandling,promotingrobustcodebutincreasingverbosity.2)JavaandPython'sexceptionsallowforcleanercodebutcanleadtooverlookederrorsifnotmanagedcare

Best Practices for Designing Effective Interfaces in GoBest Practices for Designing Effective Interfaces in GoMay 03, 2025 am 12:18 AM

AneffectiveinterfaceinGoisminimal,clear,andpromotesloosecoupling.1)Minimizetheinterfaceforflexibilityandeaseofimplementation.2)Useinterfacesforabstractiontoswapimplementationswithoutchangingcallingcode.3)Designfortestabilitybyusinginterfacestomockdep

Centralized Error Handling Strategies in GoCentralized Error Handling Strategies in GoMay 03, 2025 am 12:17 AM

Centralized error handling can improve the readability and maintainability of code in Go language. Its implementation methods and advantages include: 1. Separate error handling logic from business logic and simplify code. 2. Ensure the consistency of error handling by centrally handling. 3. Use defer and recover to capture and process panics to enhance program robustness.

Alternatives to init Functions for Package Initialization in GoAlternatives to init Functions for Package Initialization in GoMay 03, 2025 am 12:17 AM

InGo,alternativestoinitfunctionsincludecustominitializationfunctionsandsingletons.1)Custominitializationfunctionsallowexplicitcontroloverwheninitializationoccurs,usefulfordelayedorconditionalsetups.2)Singletonsensureone-timeinitializationinconcurrent

Type Assertions and Type Switches with Go InterfacesType Assertions and Type Switches with Go InterfacesMay 02, 2025 am 12:20 AM

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

Using errors.Is and errors.As for Error Inspection in GoUsing errors.Is and errors.As for Error Inspection in GoMay 02, 2025 am 12:11 AM

Go language error handling becomes more flexible and readable through errors.Is and errors.As functions. 1.errors.Is is used to check whether the error is the same as the specified error and is suitable for the processing of the error chain. 2.errors.As can not only check the error type, but also convert the error to a specific type, which is convenient for extracting error information. Using these functions can simplify error handling logic, but pay attention to the correct delivery of error chains and avoid excessive dependence to prevent code complexity.

Performance Tuning in Go: Optimizing Your ApplicationsPerformance Tuning in Go: Optimizing Your ApplicationsMay 02, 2025 am 12:06 AM

TomakeGoapplicationsrunfasterandmoreefficiently,useprofilingtools,leverageconcurrency,andmanagememoryeffectively.1)UsepprofforCPUandmemoryprofilingtoidentifybottlenecks.2)Utilizegoroutinesandchannelstoparallelizetasksandimproveperformance.3)Implement

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

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.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools