How do you time a function in Go and return its runtime in milliseconds?

The Puma

How do you time a function in Go and return its runtime in milliseconds?

peterSO

Use the Go testing package to benchmark the function. For example,

package main

import (
    "fmt"
    "testing"
)

// the function to be benchmarked
func Function(n int) int64 {
    n64 := int64(n)
    return n64 * n64
}

func BenchmarkFunction(b *testing.B) {
    n := 42
    for i := 0; i < b.N; i++ {
        _ = Function(n)
    }
}

func main() {
    br := testing.Benchmark(BenchmarkFunction)
    fmt.Println(br)
}

Output:

500000000            4.22 ns/op

You can also use the Go gotest command to run benchmarks.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to convert iso date time with milliseconds to date time format in php so that milliseconds don't go away?

How do you execute a program in Go and return to the parent process?

How do you convert a time offset to a location/timezone in Go

Why do you sometimes have a return value in parens, but sometimes not in a Go function signature?

How to get current time in milliseconds using Go language?

How do you create a new instance of a struct from its type at run time in Go?

How do you get a function pointer to a typed function in go?

Go - time - milliseconds

How do you return an object from a function?

How do you convert Milliseconds into a Javascript UTC date?

How do you unwrap a Result on Ok or return from the function on Err?

How to convert milliseconds to time

How do you return multiple function values to multiple global variables?

JavaScript/jQuery: How do you pass an element to a function as its 'this'?

How do you return object from "__main__" python function?

How do you return a string array inside a recursive function or copy it?

How do you create a timespan from milliseconds in powershell?

How to convert date to milliseconds in runtime?

How do you call a function defined in the current function by its name (a string)

How do I make btn01 or btn go to a random spot every 4 milliseconds and when you click on it it will stop and do something else?

What is `isLiveLiteralsEnabled` function in the Compose runtime and how do I disable its use?

How do you calculate time complexity for a function that has function within?

How do you return multiple variables from a function in python

How to measure time difference in milliseconds in a function?

SPARQL: how do you also return the entity and not only its propery?

How can you define a function who's return type depends on the value of its parameter?

How do you wait for a return from a function before moving on in node

How do you get multiple urls at the same time in a synchronus function

How do you get the return type of a function in jsdoc?