Sobes.tech
Junior — Senior

Decorator with execution time limit and logging for slow function

livecode

Task condition

It is required to write a wrapper around a function that can run indefinitely and return an integer value. The body of this function cannot be changed — imagine that it performs a network request or another heavy operation. The wrapper should run the function with a set timeout (for example, one second): if the function completes within the allotted time, return its result; otherwise, return an error, and ignore the obtained result. Additionally, it is necessary to measure the duration of the function execution and log it. The signature of the wrapper can be changed.

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func init() {
    rand.Seed(time.Now().UnixNano())
}

// There is a function that runs indefinitely and returns a number.
// Its body cannot be changed (imagine it performs a network request).
func unpredictableFunc() int64 {
    rnd := rand.Int63n(5000)
    time.Sleep(time.Duration(rnd) * time.Millisecond)
    return rnd
}

// The wrapper function needs to be modified to work with a specified timeout (for example, 1 second).
// If the "long" function completes within this time — great, return the result.
// If not — return an error. The result of the execution in this case is not important.
// Additionally, measure how long this function took to execute (simply log it).
// The signature of the wrapper function can be changed.
func predictableFunc() int64 {
    return unpredictableFunc()
}

func main() {
    fmt.Println("Started")
    fmt.Println(predictableFunc())
}