简体   繁体   中英

How can I measure execution time of a Python program (functional structure)?

I need to measure the execution time of a Python program having the following structure:

import numpy
import pandas

def func1():
    code

def func2():
    code

if __name__ == '__main__':

    func1()
    func2()

If I want to use "time.time()", where should I put them in the code? I want to get the execution time for the whole program.

Alternative 1:

import time
start = time.time() 

import numpy
import pandas

def func1():
    code

def func2():
    code


if __name__ == '__main__':

    func1()
    func2()


end = time.time()
print("The execution time is", end - start)

Alternative 2:

import numpy
import pandas

def func1():
    code

def func2():
    code


if __name__ == '__main__':
    import time
    start = time.time() 

    func1()
    func2()

    end = time.time()
    print("The execution time is", end - start)

In linux: you could run this file test.py using the time command

time python3 test.py

After your program runs it will give you the following output:

real 0m0.074s
user 0m0.004s
sys 0m0.000s

this link will tell the difference between the three times you get

The whole program:

import time
t1 = time.time() 

import numpy
import pandas

def func1():
    code

def func2():
    code

if __name__ == '__main__':

    func1()
    func2()

t2 = time.time()
print("The execution time is", t2 - t1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM