How do I get time of a Python program's execution?
我有一个用python编写的命令行程序,需要一段时间才能完成。我想知道跑完全程的确切时间。
我看过timeit模块,但它似乎只针对代码的小片段。我想给整个节目计时。
   TP在Python的方式:   > 
| 12
 3
 4
 
 | import timestart_time = time.time()
 main()
 print("--- %s seconds ---" % (time.time() - start_time))
 | 
   这是你的程序以assumes至少十二跑银行。   > 
   prints:   > 
| 1
 | --- 0.764891862869 seconds --- | 
 
		
		
- 这将计算实时(包括其他程序使用的时间),因此当您的计算机忙于处理其他事情时,似乎需要更多的时间。
- 在Windows上,执行相同的操作,但使用time.clock()而不是time.time()。你会得到更好的准确度。
- 保罗的答案更好,见stackoverflow.com/questions/1557571/…
- 我必须加上"导入时间"才能使其生效。
- 我建议你用round(time.time() - start_time, 2)(或者任何你想要的十进制),我得到的科学数字是1.24e-5。
- @雷神召唤师:你可能想用'%.2f'代替round()。
- @coreygoldberg:如果你想在Windows上使用time.clock(),在其他系统上使用time.time(),那么就使用timeit.default_timer()。它是最新版本的python上的time.perf_counter()。虽然在较大的时间间隔(天),time.time()可能会在任何地方产生更好的结果。
- 如何计算/控制/转换为小时、天等?
- 使用timeit模块
- 这种方法有一个很大的缺陷。如果程序运行时系统时间发生变化(如与时间服务器同步),则此方法将无法工作,甚至可能会中断代码(负持续时间…)
 
	 
   他们把这个timing.py模块在我自己的site-packages*就插入目录,我import timing在顶部模块:   > 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 
 | import atexitfrom time import clock
 
 def secondsToStr(t):
 return"%d:%02d:%02d.%03d" % \
 reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
 [(t*1000,),1000,60,60])
 
 line ="="*40
 def log(s, elapsed=None):
 print line
 print secondsToStr(clock()), '-', s
 if elapsed:
 print"Elapsed time:", elapsed
 print line
 print
 
 def endlog():
 end = clock()
 elapsed = end-start
 log("End Program", secondsToStr(elapsed))
 
 def now():
 return secondsToStr(clock())
 
 start = clock()
 atexit.register(endlog)
 log("Start Program")
 | 
 
   我可以从我的程序和呼叫timing.log内如果有重大阶段内的程序我想秀。但只是将包括import timing王子的开始和结束时间,和整体elapsed时代。(原谅我的secondsToStr晦涩的功能,它只是他浮点格式HH:MM秒到编号:ss.sss形态。)   > 
   注:以上3版本的Python代码,在这里他们可以找到这里。   > 
		
		
- 这是一个真正干净的解决方案,如果按ctrl-c停止程序,它也可以工作。
- 非常好的解决方案,并且易于与现有代码集成。谢谢!
- 很好的解决方案,我一定会使用它并创建一个时间修饰器来识别瓶颈函数。
- @c24b-查看profilehooks:pypi.python.org/pypi/profilehooks
- 很好,非常感谢。我重写了模块。我应该知道它是存在的。谢谢你指点我!
- 对于python 3,在顶部添加from functools import reduce,并在每个打印语句周围加上括号。工作很棒!
- @PowerApp101-谢谢-Nicojo的答案提供了该模块的PY3友好版本。
- 注意:time.clock()是"自3.3版以来被弃用的:此函数的行为取决于平台:根据您的要求,使用perf_counter()[with time sleed]或process_time()[without time sleed]来拥有定义良好的行为。"
- 我喜欢这个解决方案,但它会由于未使用的导入而产生一个难看的警告。除此之外,虽然可以简化为更少的行,但效果很好
 
	  
   在Linux或Unix:   > 
| 1
 | time python yourprogram.py | 
 
   在Windows,看这stackoverflow measure的讨论:如何在Windows命令行命令的执行时间行吗?   > 
		
		
- 所以,如果我正在启动另一个小部件,例如在qt应用程序中,我们如何计算该小部件显示所用的时间?
- 对于小部件案例,如果您从python程序启动,请使用rogeriopvl接受的答案。
- 但这似乎并没有给时间以分钟为单位:秒,最后是一个浮点数!!
- 是的,它会给出几秒钟的时间。如果需要,可以转换为min:seconds。看看保罗·麦奎尔的答案和它的secondsToStr()函数。
- viva la linux,很简单
 
	  
| 12
 3
 4
 5
 
 | import time
 start_time = time.clock()
 main()
 print time.clock() - start_time,"seconds"
 | 
   time.clock()再战江湖的处理器时间,这允许我们到这只使用备用时间计算过程(在任何UNIX)。文件说,"在任何住宅的使用功能,这是他们对Python的定时算法为基准"   > 
		
		
- time.time()最好用于*nix。time.clock()最好在Windows上使用。
- 我认为这不能用来计算"只有这个过程使用的时间",因为它使用系统时间,并且会受到其他系统过程的影响?如果我错了,请纠正我:)
- 注意:time.clock()是"自3.3版以来被弃用的:此函数的行为取决于平台:根据您的要求,使用perf_counter()[with time sleed]或process_time()[without time sleed]来拥有定义良好的行为。"
 
	 
 
   我真的喜欢保罗麦奎尔的回答,但我用python3。所以对那些感兴趣的是:"他对他的回答,厂用Python 3在线*nix(Windows下图像点,那应该是(),而不是用时间())):   > 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 
 | #python3import atexit
 from time import time, strftime, localtime
 from datetime import timedelta
 
 def secondsToStr(elapsed=None):
 if elapsed is None:
 return strftime("%Y-%m-%d %H:%M:%S", localtime())
 else:
 return str(timedelta(seconds=elapsed))
 
 def log(s, elapsed=None):
 line ="="*40
 print(line)
 print(secondsToStr(), '-', s)
 if elapsed:
 print("Elapsed time:", elapsed)
 print(line)
 print()
 
 def endlog():
 end = time()
 elapsed = end-start
 log("End Program", secondsToStr(elapsed))
 
 start = time()
 atexit.register(endlog)
 log("Start Program")
 | 
   如果你找到这还是有用的,你应该相信他的答案,而不是等他做到了这一个,我大部分的工作;)。   > 
		
		
- 我发现timedelta(seconds=t).total_seconds()很有用。
- 你能解释一下这些功能的作用吗?日志命令中有什么?什么是出口?
- @简而言之,这些函数打印出与之一起使用的程序的执行时间。s是日志的第一个参数,应该是一个字符串。Log是一个打印计时信息的函数。ATEXIT是一个Python模块,它允许您注册在程序出口调用的函数。
 
	 
   你可以使用Python cprofile to measure的CPU时间和事件探查器additionally花了多少时间是在每个时代,每个功能和功能的电话是多少。这是非常有用的,如果你想提高你的脚本的性能不知道在哪里开始。另一个问题的答案,所以这是很好的。它总是好的有点太在文档的外观。   > 
  "这一年以如何配置脚本从命令行使用cprofile   > | 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 
 | $ 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}
 | 
		
		
- 这个答案使我的代码保持干净。
- @杰克瓦,你怎么计算总时间?
- @查克的第一行写的是X function calls in Y CPU seconds。如果你想要挂钟时间,请在这里使用其他答案之一。
 
	 
   他喜欢datetime输出模块提供的对象,在三角洲的节目时间7天,小时,分钟,等。人在读我的必要方式。   > 
   为实例:   > | 12
 3
 4
 5
 
 | from datetime import datetimestart_time = datetime.now()
 # do your work here
 end_time = datetime.now()
 print('Duration: {}'.format(end_time - start_time))
 | 
   如样品输出   > 
| 1
 | Duration: 0:00:08.309267 | 
   他们   > 
| 1
 | Duration: 1 day, 1:51:24.269711 | 
   更新:我mentioned塞巴斯蒂安的做法,这可能与当地时间encounter一些棘手的案件,所以它对使用?   > 
| 12
 3
 4
 5
 
 | import timefrom datetime import timedelta
 start_time = time.monotonic()
 end_time = time.monotonic()
 print(timedelta(seconds=end_time - start_time))
 | 
		
		
- @范森:你可以在这里使用timedelta(seconds=time.monotonic()-start)(如果间隔比较大,可以使用time.time())。不要减去表示本地时间的简单日期时间对象;本地时间不是单调的
- 好吧,你的意思是像start_time = time.monotonic(); end_time = time.monotonic(); timedelta(seconds=end_time - start_time)。我相信你是对的,但是当你回来的时候,你也必须把它格式化。另外,似乎只有在python 3中添加了单调方法。
- 啊,好吧。我看你可以把它传给str(),让它成为"人类"。我会更新答案,谢谢。
 
	 
   Linux:/usr/bin/time更好。   > 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 
 | $ /usr/bin/time -v python rhtest2.py
 Command being timed:"python rhtest2.py"
 User time (seconds): 4.13
 System time (seconds): 0.07
 Percent of CPU this job got: 91%
 Elapsed (wall clock) time (h:mm:ss or m:ss): 0:04.58
 Average shared text size (kbytes): 0
 Average unshared data size (kbytes): 0
 Average stack size (kbytes): 0
 Average total size (kbytes): 0
 Maximum resident set size (kbytes): 0
 Average resident set size (kbytes): 0
 Major (requiring I/O) page faults: 15
 Minor (reclaiming a frame) page faults: 5095
 Voluntary context switches: 27
 Involuntary context switches: 279
 Swaps: 0
 File system inputs: 0
 File system outputs: 0
 Socket messages sent: 0
 Socket messages received: 0
 Signals delivered: 0
 Page size (bytes): 4096
 Exit status: 0
 | 
   normally,只是简单的壳time是内置的,更多的capable /usr/bin/time阴影。   > 
  "哦rogeriopvl厂细解,如果你想要更多具体的信息,你可以使用Python内置分析器。检查本页:   > 
   http:/ / /图书馆/ profile.html docs.python.org   >    他可以告诉你很多有用的信息,在每一个时代的像和功能   >  
下面的代码片段以一种很好的人类可读的格式打印经过的时间。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 
 | import timefrom datetime import timedelta
 
 start_time = time.time()
 
 #
 # Perform lots of computations.
 #
 
 elapsed_time_secs = time.time() - start_time
 
 msg ="Execution took: %s secs (Wall clock time)" % timedelta(seconds=round(elapsed_time_secs))
 
 print(msg)
 | 
		
		
- 一直到这里,人们都能找到最理智的答案("理智"的意思是尽可能多地依赖于内置的,因此打字最少)。
 
	 
   time.clock()   > 
Deprecated since version 3.3: The behavior of this function depends
  on the platform: use perf_counter() or process_time() instead,
  depending on your requirements, to have a well-defined behavior.
   time.perf _(CS)   > 
Return the value (in fractional seconds) of a performance counter,
  i.e. a clock with the highest available resolution to measure a short
  duration. It does include time elapsed during sleep and is
  system-wide.
   time.process _时间()   > 
Return the value (in fractional seconds) of the sum of the system and
  user CPU time of the current process. It does not include time elapsed
  during sleep.
| 12
 3
 
 | start = time.process_time()... do something
 elapsed = (time.process_time() - start)
 | 
| 12
 3
 4
 5
 6
 7
 
 | from time import timestart_time = time()
 ...
 end_time = time()
 time_taken = end_time - start_time # time_taken is in seconds
 hours, rest = divmod(time_taken,3600)
 minutes, seconds = divmod(rest, 60)
 | 
  "timeit ipython"任何脚本:   > 
| 12
 3
 
 | def foo():%run bar.py
 timeit foo()
 | 
I've looked at the timeit module, but it seems it's only for small snippets of code. I want to time the whole program.
| 1
 | $ python -mtimeit -n1 -r1 -t -s"from your_module import main""main()" | 
   它的运行时间和功能的一your_module.main()王子变time.time()elapsed功能我用计时器。   > 
   在Python Python /usr/bin/timeEEA对emulate /usr/bin子过程与时间/时间:如何捕捉信息,但忽略所有其他产出?。   >    cpu time to measure(如时间,不包括在time.sleep())为每个模块的功能,你可以用profile(在线cProfilePython 2):   > | 1
 | $ python3 -mprofile your_module.py | 
   你可以通过命令行来timeit-p以上如果你想我用同样的profile定时器模块的使用。   > 
   我可以看到你的Python脚本配置?   >  
只需使用timeit模块即可。它同时适用于python 2和python 3
| 12
 3
 4
 5
 6
 7
 8
 
 | import timeit
 start = timeit.default_timer()
 #ALL THE PROGRAM STATEMETNS
 stop = timeit.default_timer()
 execution_time = stop - start
 
 print("Program Executed in"+execution_time) #It returns time in sec
 | 
它以秒为单位返回,您可以有自己的执行时间。很简单,但您应该在启动程序执行的主函数中编写这些代码。如果你想得到执行时间,即使你得到了错误,那么就把你的参数"start"带到它上面,然后像这样计算它。
| 12
 3
 4
 5
 6
 7
 8
 
 | def sample_function(start,**kwargs):try:
 #your statements
 Except:
 #Except Statements
 stop = timeit.default_timer()
 execution_time = stop - start
 print("Program Executed in"+execution_time)
 | 
   我喜欢Paul McGuire和答案来了太suited形态与背景,我的经理的需求。   > 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 
 | import datetime as dtimport timeit
 
 class TimingManager(object):
 """Context Manager used with the statement 'with' to time some execution.
 
 Example:
 
 with TimingManager() as t:
 # Code to time
 """
 
 clock = timeit.default_timer
 
 def __enter__(self):
 """
 """
 self.start = self.clock()
 self.log('
 => Start Timing: {}')
 
 return self
 
 def __exit__(self, exc_type, exc_val, exc_tb):
 """
 """
 self.endlog()
 
 return False
 
 def log(self, s, elapsed=None):
 """Log current time and elapsed time if present.
 :param s: Text to display, use '{}' to format the text with
 the current time.
 :param elapsed: Elapsed time to display. Dafault: None, no display.
 """
 print s.format(self._secondsToStr(self.clock()))
 
 if(elapsed is not None):
 print 'Elapsed time: {}
 '.format(elapsed)
 
 def endlog(self):
 """Log time for the end of execution with elapsed time.
 """
 self.log('=> End Timing: {}', self.now())
 
 def now(self):
 """Return current elapsed time as hh:mm:ss string.
 :return: String.
 """
 return str(dt.timedelta(seconds = self.clock() - self.start))
 
 def _secondsToStr(self, sec):
 """Convert timestamp to h:mm:ss string.
 :param sec: Timestamp.
 """
 return str(dt.datetime.fromtimestamp(sec))
 | 
   这有一个timeit模块可以用于Python代码的执行时间的时期。   它具有详细的文档和实例在Python文档(docs.python.org https:/ / / / 2 /图书馆/ timeit.html)   > 
		
		
- OP在问题中明确提到了timeit。问题是如何在这里使用它(或者应该在这里使用它,还有其他的选择)。这是可能的答案。
 
	 
使用测线仪。
行分析器将分析执行单个代码行所需的时间。profiler是通过cython在C语言中实现的,以减少profiler的开销。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 
 | from line_profiler import LineProfilerimport random
 
 def do_stuff(numbers):
 s = sum(numbers)
 l = [numbers[i]/43 for i in range(len(numbers))]
 m = ['hello'+str(numbers[i]) for i in range(len(numbers))]
 
 numbers = [random.randint(1,100) for i in range(1000)]
 lp = LineProfiler()
 lp_wrapper = lp(do_stuff)
 lp_wrapper(numbers)
 lp.print_stats()
 | 
结果将是:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 
 | Timer unit: 1e-06 s
 Total time: 0.000649 s
 File: <ipython-input-2-2e060b054fea>
 Function: do_stuff at line 4
 
 Line #      Hits         Time  Per Hit   % Time  Line Contents
 ==============================================================
 4                                           def do_stuff(numbers):
 5         1           10     10.0      1.5      s = sum(numbers)
 6         1          186    186.0     28.7      l = [numbers[i]/43 for i in range(len(numbers))]
 7         1          453    453.0     69.8      m = ['hello'+str(numbers[i]) for i in range(len(numbers))]
 | 
对于使用Jupyter笔记本的数据人员在一个单元中,可以使用jupyter的%%timemagic命令来测量执行时间:
| 12
 
 | %%time [ x**2 for x in range(10000)]
 | 
产量CPU时间:用户4.54 ms,系统0 ns,总计4.54 ms壁时间:4.12 ms
这将只捕获特定单元的执行时间。如果要捕获整个笔记本(即程序)的执行时间,可以在同一目录中创建一个新笔记本,并在新笔记本中执行所有单元格:
假设上面的笔记本叫做example_notebook.ipynb。在同一目录下的新笔记本中:
| 12
 3
 4
 5
 
 | # Convert your notebook to a .py script:!jupyter nbconvert --to script example_notebook.ipynb
 
 # Run the example_notebook with -t flag for time
 %run -t example_notebook
 | 
产量IPython CPU计时(估计):用户:0.00秒。系统:0.00 s。墙时间:0.00 s。
 
TimeIt是Python中用于计算小代码块执行时间的类。
默认的_timer是此类中的一个方法,用于测量墙时钟计时而不是CPU执行时间。因此,其他进程执行可能会干扰这一点。因此,它对小代码块很有用。
代码示例如下:
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | from timeit import default_timer as timer
 start= timer()
 
 #some logic
 
 end = timer()
 
 print("Time taken:", end-start)
 | 
我使用了一个非常简单的函数来计时代码执行的一部分:
| 12
 3
 4
 
 | import timedef timing():
 start_time = time.time()
 return lambda x: print("[{:.2f}s] {}".format(time.time() - start_time, x))
 | 
要使用它,只需在代码前调用它来度量检索定时函数,然后在代码后调用带有注释的函数,时间将出现在注释前面,例如:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 
 | t = timing()train = pd.read_csv('train.csv',
 dtype={
 'id': str,
 'vendor_id': str,
 'pickup_datetime': str,
 'dropoff_datetime': str,
 'passenger_count': int,
 'pickup_longitude': np.float64,
 'pickup_latitude': np.float64,
 'dropoff_longitude': np.float64,
 'dropoff_latitude': np.float64,
 'store_and_fwd_flag': str,
 'trip_duration': int,
 },
 parse_dates = ['pickup_datetime', 'dropoff_datetime'],
 )
 t("Loaded {} rows data from 'train'".format(len(train)))
 | 
然后输出如下:
| 1
 | [9.35s] Loaded 1458644 rows data from 'train' | 
这样我觉得有点优雅。
   这是保罗麦奎尔的回答,我厂。房子是有麻烦的人只是在奔跑的那一个。   > 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 
 | import atexitfrom time import clock
 
 def reduce(function, iterable, initializer=None):
 it = iter(iterable)
 if initializer is None:
 value = next(it)
 else:
 value = initializer
 for element in it:
 value = function(value, element)
 return value
 
 def secondsToStr(t):
 return"%d:%02d:%02d.%03d" % \
 reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
 [(t*1000,),1000,60,60])
 
 line ="="*40
 def log(s, elapsed=None):
 print (line)
 print (secondsToStr(clock()), '-', s)
 if elapsed:
 print ("Elapsed time:", elapsed)
 print (line)
 
 def endlog():
 end = clock()
 elapsed = end-start
 log("End Program", secondsToStr(elapsed))
 
 def now():
 return secondsToStr(clock())
 
 def main():
 start = clock()
 atexit.register(endlog)
 log("Start Program")
 | 
   从你的呼叫timing.main()进口后的程序文件。   > 
要使用metakermit对python 2.7的更新答案,您需要单调的包。
代码如下:
| 12
 3
 4
 5
 6
 
 | from datetime import timedeltafrom monotonic import monotonic
 
 start_time = monotonic()
 end_time = monotonic()
 print(timedelta(seconds=end_time - start_time))
 | 
在python中可以得到一个非常简单的方法,不需要做太复杂的事情。
   import time
   start = time.localtime()
   end = time.localtime()
  """Total execution time in second$"""
   print(end.tm_sec - start.tm_sec)
 
python程序执行度量的时间可能不一致,具体取决于:
- 相同的程序可以使用不同的算法进行评估
- 运行时间因算法而异
- 运行时间因实现而异
- 运行时间因计算机而异
- 基于小输入,运行时间不可预测。
这是因为最有效的方法是使用"增长顺序"并学习大的"O"符号来正确地完成它,https://en.wikipedia.org/wiki/big_o_notation
无论如何,您可以尝试使用以下简单算法以每秒特定的机器计数步骤评估任何python程序的性能:使其适应您要评估的程序
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | import time
 now = time.time()
 future = now + 10
 step = 4 # why 4 steps? because until here already 4 operations executed
 while time.time() < future:
 step += 3 # why 3 again? because while loop execute 1 comparison and 1 plus equal statement
 step += 4 # why 3 more? because 1 comparison starting while when time is over plus final assignment of step + 1 and print statement
 print(str(int(step / 10)) +" steps per second")
 | 
希望这对你有帮助。
如果你想以微秒为单位测量时间,那么你可以使用以下版本,完全基于保罗·麦奎尔和尼科霍的答案——这是一个python3代码。我还添加了一些颜色:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 
 | import atexitfrom time import time
 from datetime import timedelta, datetime
 
 
 def seconds_to_str(elapsed=None):
 if elapsed is None:
 return datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
 else:
 return str(timedelta(seconds=elapsed))
 
 
 def log(txt, elapsed=None):
 colour_cyan = '\033[36m'
 colour_reset = '\033[0;0;39m'
 colour_red = '\033[31m'
 print('
 ' + colour_cyan + '  [TIMING]> [' + seconds_to_str() + '] ----> ' + txt + '
 ' + colour_reset)
 if elapsed:
 print("
 " + colour_red +" [TIMING]> Elapsed time ==>" + elapsed +"
 " + colour_reset)
 
 
 def end_log():
 end = time()
 elapsed = end-start
 log("End Program", seconds_to_str(elapsed))
 
 
 start = time()
 atexit.register(end_log)
 log("Start Program")
 | 
log()=>打印计时信息的函数。
txt==>要记录的第一个参数,它是标记时间的字符串。
ATEXIT==>python模块注册程序退出时可以调用的函数。