Trying to write a decorator, which displays the execution time of the function. Please tell me what's wrong. Thanks

import time def time_of_function(function): def wrapped(first, second): start_time = time.clock() function(bin(int(str(first), 2)+int(str(second), 2))) print(time.clock() - start_time) return wrapped @time_of_function def time_of_func(function): print(function(111,0000)) 

    1 answer 1

    Apparently, you wanted to do this. The main error: in the decorator does not need the implementation of the function. The logic of the function is inside the function.

     import time def time_of_function(function): def wrapped(*args): start_time = time.clock() res = function(*args) print(time.clock() - start_time) return res return wrapped @time_of_function def func(first, second): return bin(int(first, 2) + int(second, 2)) print(func("111", "0000")) 
    • Thank you very much. It has become clearer ... it seems)) !!! But I didn’t quite understand why return res. I will pick further.Thanks - Valery
    • @Valery to return the value to the calling code. You can, of course, make an output ( print ) of the value directly in the called function, but this is a side effect, which in some cases can complicate the understanding of the code. It is better to assume that the function should calculate the value and return it to the outside. And what to do with it further, is the next question. - mkkik
    • Thank you, you explained very clearly! - Valery