2015年6月25日 星期四

[ Python 常見問題 ] Python speed testing - Time Difference - milliseconds

Source From Here 
Question 
What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand thetimedelta thing. So far I have this code: 
  1. from datetime import datetime  
  2.   
  3. tstart = datetime.now()  
  4. print t1  
  5.   
  6. # code to speed test  
  7.   
  8. tend = datetime.now()  
  9. print t2  
  10. # what am I missing?  
  11. # I'd like to print the time diff here  
How-To 
datetime.timedelta is just the difference between two datetimes ... so it's like a period of time, in days / seconds / microseconds: 
>>> import datetime
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> c = b - a

>>> c
datetime.timedelta(0, 4, 316543)
>>> c.days
0
>>> c.seconds
4
>>> c.microseconds
316543

Be aware that c.microseconds only returns the microseconds portion of the timedelta! For timing purposes always use c.total_seconds(). You can do all sorts of maths with datetime.timedelta, eg: 
>>> c / 10
datetime.timedelta(0, 0, 431654)

It might be more useful to look at CPU time instead of wallclock time though ... that's operating system dependant though ... under Unix-like systems, check out the 'time' command.

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...