Python time measurement script

I have had this question for a long time, and I have been looking for the answer in several places without success ...

My question is: how to measure the time it takes to execute a full script?

Imagine I had this stupid script to calculate the sum of all numbers from 0 to 10 ^ 12:

x = 0
for i in range(pow(10,12)):
    x += i
print(x)

How do I know how long it took for my PC?

Thanks in advance, RSerrao

+4
source share
3 answers

python cProfile , , . , script, , . SO . .

, script cProfile :

$ python -m cProfile euler048.py

1007 function calls in 0.061 CPU seconds

Ordered by: standard name
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.000    0.000    0.061    0.061 <string>:1(<module>)
 1000    0.051    0.000    0.051    0.000 euler048.py:2(<lambda>)
    1    0.005    0.005    0.061    0.061 euler048.py:2(<module>)
    1    0.000    0.000    0.061    0.061 {execfile}
    1    0.002    0.002    0.053    0.053 {map}
    1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler objects}
    1    0.000    0.000    0.000    0.000 {range}
    1    0.003    0.003    0.003    0.003 {sum}
+9

IPython, %timeit ( , ):

%timeit [x for x in range(1000)]

( ):

10000 loops, best of 3: 37.1 ยตs per loop

script, :

def sumx(y,z):
    x = 0
    for i in range(pow(y,z)):
        x += 1
    print(x)

do:

%timeit sumx(5,7)

:

100 loops, best of 3: 4.85 ms per loop
+2

, :

import time
# at the beginning:
start_time = time.time()

# at the end of the program:
print("%f seconds" % (time.time() - start_time))

100% ,

+1

All Articles