1

How can I make a python wrapper script that would measure the execution time of another script or another .py file using time?

0

2 Answers 2

0

You can use the timer module

from timeit import default_timer as timer
start = timer()
function_you_want_to_time()
# or import your script here
# import script_to_time
end = timer()
elapsed = str(end - start)
print(f'Run time in seconds: {elapsed}')
Sign up to request clarification or add additional context in comments.

2 Comments

I actually need to time the whole script not the function inside of the script. Example I have a benchrun.py , I need to get its execution time using wrapper.py
It still works, just replace function_you_want_to_time() with import benchrun
0

I had a similar problem to solve recently, my solution was to write an importable module that I could call via import MyModule that would capture script execution times along with any runtime exceptions and then push the results to a data warehouse.

My solution looked like this

import MyModule

def main():
    print("do work")

if __main__ == '__main__':
    try:
        main()
    except Exception as e:
        MyModule.script.script_execution(e)
    else:
        MyModule.script.script_execution()

The MyModule would like something like this

MyModule.__init__.py

from datetime import datetime


class ScriptExeuction:
    def __init__(self):
        self.start_time = datetime.now()

    def script_execution(self, exception=None):
        self.end_time = datetime.now()
        print(f"Execution took {self.end_time - self.start_time}")


if __name__ == '__main__':
    pass
else:
    script = ScriptExeuction()

Naturally you would need to extend this to put the data where you want it, but you can easily extend the ScriptExecution class to handle the logic of pushing your data somewhere and you can capture the exceptions that occur in the script.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.