Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging execution time with decorators [closed]

After I tried unsuccessfully for a while, I am seeking help from this miraculous website. Now for my problem: I want to create a decorator that writes the elapsed execution time of a function (during the execution of the function) into a logging file like:

@log_time("log.txt", 35)
def some_function(...):
    ...
    return result

and

from functools import wraps

def log_time(path_to_logfile, interval):
    ...

so that log.txt would look something like

Time elapsed: 0h 0m 35s
Time elapsed: 0h 1m 10s
Time elapsed: 0h 1m 45s

Any ideas?

like image 593
Kaleidophon Avatar asked Dec 15 '22 09:12

Kaleidophon


1 Answers

I'll give you the basic overview about what you must do in order to accomplish this. The following is a decorator that accepts two parameters, and executes the function. The missing funcitonality is presented as comments, add them in:

def log_time(path_to_logfile, interval):
    def log(func):
        # 'wrap' this puppy up if needed 
        def wrapped(*args, **kwargs):
            # start timing
            func(*args, **kwargs)
            # stop timing
            with open(path_to_logfile, 'a') as f:
                pass # functionality
        return wrapped
    return log

You can now decorate functions and the output is going to be written in path_to_logfile. So, for example, decorating foo here:

@log_time('foo.txt', 40)
def foo(i, j):
    print(i, j)

foo(1, 2)

Will take foo and execute it. You need to time it appropriately and write the contents to your file. You should experiment with decorators even more and read up on them, a nice article on Decorators exist at the Python Wiki.

like image 144
Dimitris Fasarakis Hilliard Avatar answered Jan 11 '23 22:01

Dimitris Fasarakis Hilliard