Measure function execution time elegantly in Rust(Python, Golang)
Table of Contents
Measuring function time is quite necessary sometimes. It is easy to implement this in other languages but not in Rust. Therefore, this post will demonstrate some tricks to measure the function execution time.
From the easiest one to the reusable version. Other implementation will also be included, such as Python and Golang.
Basic version
In any language, you can complete this task simply by calculating the time differences to measure the exection time.
For example,
This implementation is easy but not elegant. Not reusable as well.
Reusable version
TL;DR: In Rust
Use this:
// https://stackoverflow.com/a/25182801/8587335
We will take a few examples from Python and Golang to demonstrate what we want exactly.
In Python
Writing python is easy and comfortable although it sacrifices the most important performance.
You can achieve this purpose by the following code:
# more detail: https://stackoverflow.com/a/803626/8587335
=
=
=
# function is passwd as a parameter using lambda feature
# you can reuse the code again without writing time-related codes
In Golang
It is not easy to write similar code like python in Golang.
But Golang has defer to work with. Great news!
This version of code is the most simplest and practical I could find. You may want to use this as well.
// Comes from: https://dev.to/rubiin/measure-function-execution-time-in-golang-177l
func measureTime(start time.Time, name string)
func expensive_func()
In Rust
It is much harder to write similar code like Python and Golang in Rust since passing function as a argument is really hard.
At the same time, you can’t easily achieve dynamic dispatch for function argument.
But then I suddenly find this in here, which enlightens me greatly.
You can find codes in playground:
use sleep;
use ;
// https://stackoverflow.com/a/25182801/8587335