Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an efficient way to calculate execution time in golang?

I'm looking for the best way to calculate execution time in go.

func main() {     start := time.Now()      time.Sleep(time.Second * 2)      //something doing here      elapsed := time.Since(start)     fmt.Printf("page took %s", elapsed) } 

The code above works fine.

But when I use templates, I have to write it again for each template function.

Is there an efficient way of calculating execution time, including templates?

like image 985
Özgür Yalçın Avatar asked Aug 19 '17 00:08

Özgür Yalçın


People also ask

How does Lua measure time?

Measuring Execution Time. With Lua, you can measure the execution time for a script or a script chunk by using the Lua os. clock function. That function returns an approximation of the operating system's current time in seconds (including decimal fractions of a second.)

What is code execution time?

The execution time of a task is defined as the time taken by the system to execute that task. The execution time of a program is equal to the sum of the execution time of its statements.

How does C++ calculate execution time?

measure execution time of a program. Using time() function in C & C++. time() : time() function returns the time since the Epoch(jan 1 1970) in seconds. Prototype / Syntax : time_t time(time_t *tloc);


1 Answers

If you are timing an entire function, then you can use defer to eliminate some of the repetitive code.

func elapsed(what string) func() {     start := time.Now()     return func() {         fmt.Printf("%s took %v\n", what, time.Since(start))     } }  func main() {     defer elapsed("page")()  // <-- The trailing () is the deferred call     time.Sleep(time.Second * 2) } 

playground example

The specification says this about deferred calls:

Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked. Instead, deferred functions are invoked immediately before the surrounding function returns,

The function value elapsed("page") is evaluated at the defer statement. The elapsed function records the current time and returns an anonymous function. The returned anonymous function is invoked immediately before the surrounding function returns. The anonymous function computes and prints the elapsed time.

like image 137
Bayta Darell Avatar answered Sep 23 '22 18:09

Bayta Darell