search
HomeBackend DevelopmentGolangHow to get function execution time in Go language

How to get function execution time in Go language

Jan 17, 2023 am 10:23 AM
golanggo language

In the Go language, you can use the Since() function in the time package to obtain the function execution time. Set a start time before the function is executed, and obtain the time interval from the start time to the present at the end of the function execution. This time interval is the execution time of the function; and the function execution time can be calculated using the time.Since() function, The syntax "time.Since(t)" will return the time elapsed from t to now.

How to get function execution time in Go language

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

Use time.Since to calculate the execution time

The length of the function’s running time is an important indicator to measure the performance of this function, especially in comparison In benchmark tests, the simplest way to get the running time of a function is to set a starting time before the function is executed, and get the time interval from the starting time to the present when the function ends. This time interval is the function's operation hours.

In Go language, we can use the Since() function in the time package to obtain the running time of the function. The introduction of the Since() function in the official Go language documentation is as follows.

func Since(t Time) Duration

Since() function returns the time elapsed from t to now, which is equivalent to time.Now().Sub(t).

Example 1: Use the Since() function to obtain the running time of the function

package main
import (
    "fmt"
    "time"
)
func test() {
    start := time.Now() // 获取当前时间
    sum := 0
    for i := 0; i < 100000000; i++ {
        sum++
    }
    elapsed := time.Since(start)
    fmt.Println("该函数执行完成耗时:", elapsed)
}
func main() {
    test()
}

The running results are as follows:

该函数执行完成耗时: 39.8933ms

We mentioned time above The function of .Now().Sub() is similar to the Since() function. If you want to use time.Now().Sub() to obtain the running time of the function, you only need to simply modify line 14 of our code above.

Example 2: Use time.Now().Sub() to get the running time of the function

package main
import (
    "fmt"
    "time"
)
func test() {
    start := time.Now() // 获取当前时间
    sum := 0
    for i := 0; i < 100000000; i++ {
        sum++
    }
    elapsed := time.Now().Sub(start)
    fmt.Println("该函数执行完成耗时:", elapsed)
}
func main() {
    test()
}

The running results are as follows:

该函数执行完成耗时: 36.8769ms

Due to the influence of the computer's CPU and some other factors, the results obtained each time when obtaining the function running time are slightly different, which is normal.

Extended knowledge: use time.Now().Sub() to calculate the time difference

We only need to replace time.Since() with time.Now().Sub() can be used, as follows:

    start := time.Now() // 获取当前时间
    sum := 0
    for i := 0; i < 100000000; i++ {
        sum++
    }
    elapsed := time.Now().Sub(start)
    fmt.Println(elapsed)

In fact, time.Since internally calls the Sub function. Let’s enter the time package to see. The annotation means that Since returns the time that has passed since t. , time.Since is the abbreviation of time.Now().Sub(t),

\src\time\time.go 923:6

// Since returns the time elapsed since t.
// It is shorthand for time.Now().Sub(t).
func Since(t Time) Duration {
    var now Time
    if t.wall&hasMonotonic != 0 {
        // Common case optimization: if t has monotonic time, then Sub will use only it.
        now = Time{hasMonotonic, runtimeNano() - startNano, nil}
    } else {
        now = Now()
    }
    return now.Sub(t)
}

when We can also use time.Now().Sub(start).Seconds() to get the number of seconds that have passed, Hours to get the number of hours that have passed, etc. The corresponding ones can also be abbreviated as time.Since(start).Seconds(), time. Since(start).Seconds() etc.

【Related recommendations: Go video tutorial, Programming teaching

The above is the detailed content of How to get function execution time 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
Golang: The Go Programming Language ExplainedGolang: The Go Programming Language ExplainedApr 10, 2025 am 11:18 AM

The core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.

Golang's Purpose: Building Efficient and Scalable SystemsGolang's Purpose: Building Efficient and Scalable SystemsApr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Apr 02, 2025 pm 05:24 PM

Confused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...

Is technology stack convergence just a process of technology stack selection?Is technology stack convergence just a process of technology stack selection?Apr 02, 2025 pm 05:21 PM

The relationship between technology stack convergence and technology selection In software development, the selection and management of technology stacks are a very critical issue. Recently, some readers have proposed...

How to use reflection comparison and handle the differences between three structures in Go?How to use reflection comparison and handle the differences between three structures in Go?Apr 02, 2025 pm 05:15 PM

How to compare and handle three structures in Go language. In Go programming, it is sometimes necessary to compare the differences between two structures and apply these differences to the...

How to view globally installed packages in Go?How to view globally installed packages in Go?Apr 02, 2025 pm 05:12 PM

How to view globally installed packages in Go? In the process of developing with Go language, go often uses...

What should I do if the custom structure labels in GoLand are not displayed?What should I do if the custom structure labels in GoLand are not displayed?Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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.