as everyone knows ,python Medium time The module can get the timestamp , Then we get the running time of the program piece . But running time obtained by subtracting timestamps is relatively humble for large-scale programs , You have to name many variable names to record time stamps . This is the time , You can use the decorator to record the time .
This paper introduces two methods , Contrast .
Regular Edition ：
from time import time def run(): res = 0 for i in range(10000): for j in range(10000): res += 1 res -= 1 if __name__ == '__main__': start = time() # Get the timestamp of the start of the function run() end = time() # Get the timestamp of the end of the function print('time cost:', end-start) # Subtract to get the run time
decorator edition ：
from time import time def time_costing(func): def core(): start = time() func() print('time costing:', time() - start) return core @time_costing def run(): res = 0 for i in range(10000): for j in range(10000): res += 1 res -= 1 if __name__ == '__main__': run()
The advantage of using decorator to measure function time is embodied in , Just add... To the line before any function @xxx Can . It's cool and convenient , It is very useful for detailed time monitoring of large-scale programs . Clean and sanitary .
Please poke if you don't understand the decorator 《python Decorator in 》
hope it's useful to you, thanks.