search
HomeBackend DevelopmentGolangBenchmarks and performance comparison in Go language
Benchmarks and performance comparison in Go languageMay 08, 2024 am 09:27 AM
go languageBenchmarksPerformance comparison

In the Go language, you can easily write benchmark tests to measure code performance by using the BenchmarkXXX functions in the testing package. These functions follow the standard syntax and receive a pointer of type *testing.B as argument, which controls the running of the benchmark. Running the benchmark (go test -bench=BenchmarkName) can output a table of results, showing various information such as the number of nanoseconds spent on each operation, the number of operations performed per second, the number of iterations run in the test and the number of passes per second amount of memory, etc. By comparing the results of different benchmarks, you can identify inefficient code areas and thereby improve the overall performance of your application.

Benchmarks and performance comparison in Go language

Benchmarks and Performance Comparisons in the Go Language

Introduction

Benchmarks Tests are an important tool for measuring code performance. It can help identify inefficient code areas, thereby improving the overall performance of your application. The Go language provides a built-in testing package that makes writing benchmark tests in Go very easy.

Syntax

The syntax of the benchmark function is as follows:

func BenchmarkName(b *testing.B)

Where:

  • b Is a pointer of type *testing.B that contains some additional functionality for benchmarking.

Practical Case

Let’s write a benchmark to compare the performance of two different sorting algorithms:

package main

import (
    "testing"
    "bytes"
    "sort"
)

// 插入排序
func insertionSort(nums []int) {
    for i := 1; i < len(nums); i++ {
        key := nums[i]
        j := i - 1

        for j >= 0 && nums[j] > key {
            nums[j+1] = nums[j]
            j--
        }

        nums[j+1] = key
    }
}

// 快速排序
func quickSort(nums []int) {
    if len(nums) <= 1 {
        return
    }

    pivot := nums[len(nums)/2]
    var left, right []int

    for _, num := range nums {
        if num < pivot {
            left = append(left, num)
        } else if num > pivot {
            right = append(right, num)
        }
    }

    quickSort(left)
    quickSort(right)

    copy(nums, append(left, append([]int{pivot}, right...)...))
}

// 基准测试
func BenchmarkInsertionSort(b *testing.B) {
    var buf bytes.Buffer

    for i := 0; i < b.N; i++ {
        nums := []int{5, 2, 8, 3, 1, 9, 4, 7, 6}
        insertionSort(nums)
        buf.WriteString(bytes.Join(nums, " "))
    }
}

func BenchmarkQuickSort(b *testing.B) {
    var buf bytes.Buffer

    for i := 0; i < b.N; i++ {
        nums := []int{5, 2, 8, 3, 1, 9, 4, 7, 6}
        quickSort(nums)
        buf.WriteString(bytes.Join(nums, " "))
    }
}

func BenchmarkGoSort(b *testing.B) {
    var buf bytes.Buffer

    for i := 0; i < b.N; i++ {
        nums := []int{5, 2, 8, 3, 1, 9, 4, 7, 6}
        sort.Ints(nums)
        buf.WriteString(bytes.Join(nums, " "))
    }
}

Running the Benchmark

To run the benchmark, run the following command:

go test -bench=BenchmarkName

where BenchmarkName is the name of the benchmark function you want to run.

Interpretation of results

The benchmark results will be output in the form of a table, containing various information, such as:

  • ns/op : The number of nanoseconds each operation takes.
  • op/s: Number of operations performed per second.
  • B: Number of iterations run in the test.
  • MB/s: The amount of memory transferred per second.

Comparison sorting algorithm

After running the above benchmark, you will see the following results (results may vary depending on your hardware and system configuration ):

BenchmarkInsertionSort     20332432               62.5 ns/op         16 B/op               5.75 MB/s
BenchmarkQuickSort         11440808              104 ns/op          24 B/op              1.64 MB/s
BenchmarkGoSort            21864500               57.7 ns/op          32 B/op               4.77 MB/s

From these results, we can see that insertion sort is the slowest, followed by quicksort, and the fastest is sort.Ints.

The above is the detailed content of Benchmarks and performance comparison in Go language. 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
vivox100s和x100区别大揭秘:性能、设计、价格全面比较vivox100s和x100区别大揭秘:性能、设计、价格全面比较Mar 19, 2024 am 08:48 AM

vivox100s和x100区别大揭秘:性能、设计、价格全面比较随着智能手机市场的不断发展,手机品牌之间的竞争也愈发激烈。vivox100s和x100作为两款备受关注的新品,备受消费者期待。这两款手机在性能、设计、价格等方面有何异同?本文将为您进行一次全面比较。首先,让我们来看看性能方面的比较。vivox100s搭载了最新的骁龙865处理器,性能强劲,能够满

go语言为什么叫gogo语言为什么叫goNov 28, 2022 pm 06:19 PM

go语言叫go的原因:想表达这门语言的运行速度、开发速度、学习速度(develop)都像gopher一样快。gopher是一种生活在加拿大的小动物,go的吉祥物就是这个小动物,它的中文名叫做囊地鼠,它们最大的特点就是挖洞速度特别快,当然可能不止是挖洞啦。

iPad Air 5 基准测试显示与 11 英寸 iPad Pro 相同的性能iPad Air 5 基准测试显示与 11 英寸 iPad Pro 相同的性能May 18, 2023 am 10:34 AM

正如预期的那样,由于两款设备都使用了M1处理器,早期的基准测试显示iPadAir5的得分与11英寸iPadPro相同。审阅者通过Geekbench运行iPadAir5,得分并不令人惊讶。事实上,这些数字的不同之处仅在于舍入误差和每次运行的变化。iPadAir5在Geekbench中被列为“iPad13,17”,在一次CPU测试中显示了1711的单核成绩和7233的多核成绩。这与11英寸iPadPro类似,单核成绩为1718,多核成绩为7313。在

一文详解Go中的并发【20 张动图演示】一文详解Go中的并发【20 张动图演示】Sep 08, 2022 am 10:48 AM

Go语言中各种并发模式看起来是怎样的?下面本篇文章就通过20 张动图为你演示 Go 并发,希望对大家有所帮助!

【整理分享】一些GO面试题(附答案解析)【整理分享】一些GO面试题(附答案解析)Oct 25, 2022 am 10:45 AM

本篇文章给大家整理分享一些GO面试题集锦快答,希望对大家有所帮助!

go语言是编程语言吗go语言是编程语言吗Nov 28, 2022 pm 06:38 PM

go语言是编程语言。go语言又称Golang,是Google开发的一种静态强类型、编译型、并发型,并具有垃圾回收功能的编程语言。Go语言的推出,旨在不损失应用程序性能的情况下降低代码的复杂性,具有“部署简单、并发性好、语言设计良好、执行性能好”等优势。

golang函数类型的性能比较分析golang函数类型的性能比较分析Apr 28, 2024 am 10:57 AM

在Go语言中,函数类型对性能有显著影响。性能比较显示,普通函数最优(147.08MOPS),其次是匿名函数(158.01MOPS),最后是闭包(10.02MOPS)。这些类型在不同场景中有不同的优势:匿名函数适合回调,闭包适合状态管理,普通函数适合性能优化。

什么是golang什么是golangNov 22, 2022 am 10:33 AM

golang是一种静态强类型、编译型、并发型,并具有垃圾回收功能的编程语言;它可以在不损失应用程序性能的情况下极大的降低代码的复杂性,还可以发挥多核处理器同步多工的优点,并可解决面向对象程序设计的麻烦,并帮助程序设计师处理琐碎但重要的内存管理问题。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!