2

We can measure how long a script took to be executed. As in this question: How do I get time of a Python program's execution?

But what I want is to find the time it takes a code to be executed before the execution.

Example 1:

When executing a script, first thing to print is something like this:

this function will take 1 min 40 seconds to be executed

Example 2:

A percentage of how much execution is done so far. For example, after a minute the percentage is: 60% and it keep increasing until it hits 100%.

ananya
  • 879
  • 1
  • 7
  • 14

2 Answers2

1

A fully general solution to this question would solve the halting problem, which has been mathematically proven impossible.

For more particular cases, it can be done. For certain algorithms, if you know how much work must be done and you can periodically check how much of it has been done, then you can update the percentage. You can also estimate the time remaining based on how quickly the percentage is progressing, but this can often be inaccurate.

gilch
  • 10,813
  • 1
  • 23
  • 28
  • Thank you so much. I think this is how it is done in Linux when you install a package then it adds `=` for every `5%` until it finishes the whole line, something like this: `|==============|` . – ananya Aug 04 '18 at 20:08
0

Please be consider that when you are executing a function, the time depends on your algorithm as well as your machine speed. In order to calculate the time without executing the code, you may have to give some initial parameters or else use a machine learning code that will calculate the time of execution by going through the codes but it seems very difficult.

Btw Try this using import timeit.

Just save the time before and after the execution of code and subtract them! But this method is not precise as there might be a background process momentarily running which disrupts the code execution and you will get significant variations in running time of small code snippets.

timeit runs your snippet of code millions of time (default value is 1000000) so that you get the statistically most relevant measurement of code execution time!

# importing the required module import timeit

# code snippet to be executed only once
mysetup = "from math import sqrt"

# code snippet whose execution time is to be measured
mycode = '''
def example():
    mylist = []
    for x in range(100):
        mylist.append(sqrt(x))
'''

# timeit statement
print timeit.timeit(setup = mysetup,
                    stmt = mycode,
                    number = 10000)
Sathiyakugan
  • 674
  • 7
  • 20