]> SALOME platform Git repositories - tools/eficas.git/blob - Aster/Cata/Utilitai/as_timer.py
Salome HOME
CCAR: merge de la version 1.14 dans la branche principale
[tools/eficas.git] / Aster / Cata / Utilitai / as_timer.py
1 #@ MODIF as_timer Utilitai  DATE 24/09/2007   AUTEUR COURTOIS M.COURTOIS 
2 # -*- coding: iso-8859-1 -*-
3 #            CONFIGURATION MANAGEMENT OF EDF VERSION
4 # ======================================================================
5 # COPYRIGHT (C) 1991 - 2007  EDF R&D                  WWW.CODE-ASTER.ORG
6 # THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY  
7 # IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY  
8 # THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR     
9 # (AT YOUR OPTION) ANY LATER VERSION.                                                  
10 #                                                                       
11 # THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT   
12 # WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF            
13 # MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU      
14 # GENERAL PUBLIC LICENSE FOR MORE DETAILS.                              
15 #                                                                       
16 # YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE     
17 # ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,         
18 #    1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.        
19 # ======================================================================
20
21 """
22    Definition of ASTER_TIMER class.
23 """
24
25 __revision__ = "$Id: as_timer.py,v 1.2.6.1 2007-10-22 12:23:38 pnoyret Exp $"
26
27 # ----- differ messages translation
28 def _(mesg):
29    return mesg
30
31 import os
32 import time
33
34 #-------------------------------------------------------------------------------
35 def _dtimes():
36    """Returns a dict of cpu, system and total times.
37    """
38    l_t = os.times()
39    return { 'cpu'   : (l_t[0], l_t[2]),
40             'sys'   : (l_t[1], l_t[3]),
41             'tot'   : l_t[4], }
42
43 #-------------------------------------------------------------------------------
44 def _conv_hms(t):
45    """Convert a number of seconds in hours, minutes, seconds.
46    """
47    h = int(t/3600)
48    m = int(t % 3600)/60
49    s = (t % 3600) % 60
50    return h, m, s
51
52 #-------------------------------------------------------------------------------
53 #-------------------------------------------------------------------------------
54 #-------------------------------------------------------------------------------
55 class ASTER_TIMER:
56    """This class provides methods to easily measure time spent during
57    different steps.
58    Methods :
59       Start : start a timer in mode 'INIT' ([re]start from 0) or 'CONT'
60          (restart from last value).
61       Stop  : stop a timer
62    Attributes :
63       timers : dict {
64          timer_id : {
65             'name'   : timer legend (=timer_id by default),
66             'state'  : state,
67             'cpu_t0' : initial cpu time,
68             'cpu_dt' : spent cpu time,
69             'sys_t0' : initial system time,
70             'sys_dt' : spent system time,
71             'tot_t0' : start time,
72             'tot_dt' : total spent time,
73             'num'    : timer number (to print timers in order of creation),
74             'hide'   : boolean,
75          },
76          ...
77       }
78          state is one of 'start', 'stop'
79    """
80    MaxNumTimer = 9999999
81
82 #-------------------------------------------------------------------------------
83    def __init__(self, add_total=True, format='as_run'):
84       """Constructor
85       """
86       # ----- initialisation
87       self.timers = {}
88       self.add_total = add_total
89       
90       if not format in ('as_run', 'aster'):
91          format = 'as_run'
92       
93       if format == 'as_run':
94          self.fmtlig = '   %(name)-26s  %(cpu_dt)9.2f  %(sys_dt)9.2f  %(cpu_sys)9.2f  %(tot_dt)9.2f'
95          self.fmtstr = '   %(title)-26s  %(cpu)9s  %(sys)9s  %(cpu+sys)9s  %(elapsed)9s'
96          self.sepa   = ' ' + '-'*74
97          self.TotalKey = _('Total time')
98          self.d_labels = {
99             'title'   : '',
100             'cpu'     : _('cpu'),
101             'sys'     : _('system'),
102             'cpu+sys' : _('cpu+sys'),
103             'elapsed' : _('elapsed'),
104          }
105       elif format == 'aster':
106          self.fmtlig = ' * %(name)-16s : %(cpu_dt)10.2f : %(sys_dt)10.2f : %(cpu_sys)10.2f : %(tot_dt)10.2f *'
107          self.fmtstr = ' * %(title)-16s : %(cpu)10s : %(sys)10s : %(cpu+sys)10s : %(elapsed)10s *'
108          self.sepa   = ' ' + '*'*72
109          self.TotalKey = 'TOTAL_JOB'
110          self.d_labels = {
111             'title'   : 'COMMAND',
112             'cpu'     : 'USER',
113             'sys'     : 'SYSTEM',
114             'cpu+sys' : 'USER+SYS',
115             'elapsed' : 'ELAPSED',
116          }      
117       
118       self.total_key = id(self)
119       if self.add_total:
120          self.Start(self.total_key, name=self.TotalKey, num=self.MaxNumTimer)
121
122 #-------------------------------------------------------------------------------
123    def Start(self, timer, mode='CONT', num=None, hide=False, name=None):
124       """Start a new timer or restart one
125       """
126       name = name or str(timer)
127       isnew = not timer in self.timers.keys()
128       if not num:
129          num = len(self.timers)
130       if mode == 'INIT':
131          num = self.timers[timer]['num']
132       dico = _dtimes()
133       if isnew or mode == 'INIT':
134          self.timers[timer] = {
135             'name'   : name,
136             'state'  : 'start',
137             'cpu_t0' : dico['cpu'],
138             'cpu_dt' : 0.,
139             'sys_t0' : dico['sys'],
140             'sys_dt' : 0.,
141             'tot_t0' : dico['tot'],
142             'tot_dt' : 0.,
143             'num'    : num,
144             'hide'   : hide,
145          }
146       elif mode == 'CONT' and self.timers[timer]['state'] == 'stop':
147          self.timers[timer].update({
148             'state'  : 'start',
149             'cpu_t0' : dico['cpu'],
150             'sys_t0' : dico['sys'],
151             'tot_t0' : dico['tot'],
152          })
153
154 #-------------------------------------------------------------------------------
155    def Stop(self, timer, hide=False):
156       """Stop a timer
157       """
158       if not timer in self.timers.keys():
159          self.timers[timer] = {
160             'name'   : str(timer),
161             'hide'   : hide,
162             'state'  : 'stop',
163             'cpu_t0' : 0.,
164             'cpu_dt' : 0.,
165             'sys_t0' : 0.,
166             'sys_dt' : 0.,
167             'tot_t0' : 0.,
168             'tot_dt' : 0.,
169             'num': len(self.timers),
170          }
171       elif self.timers[timer]['state'] == 'start':
172          dico = _dtimes()
173          self.timers[timer]['state'] = 'stop'
174          for i in range(len(dico['cpu'])):
175             self.timers[timer]['cpu_dt'] += \
176                dico['cpu'][i] - self.timers[timer]['cpu_t0'][i]
177          self.timers[timer]['cpu_t0'] = dico['cpu']
178          for i in range(len(dico['sys'])):
179             self.timers[timer]['sys_dt'] += \
180                dico['sys'][i] - self.timers[timer]['sys_t0'][i]
181          self.timers[timer]['sys_t0'] = dico['sys']
182          self.timers[timer]['tot_dt'] = self.timers[timer]['tot_dt'] + \
183                dico['tot'] - self.timers[timer]['tot_t0']
184          self.timers[timer]['tot_t0'] = dico['tot']
185          self.timers[timer]['hide'] = hide
186
187 #-------------------------------------------------------------------------------
188    def StopAndGet(self, timer, *args, **kwargs):
189       """Stop a timer and return "delta" values.
190       """
191       self.Stop(timer, *args, **kwargs)
192       cpu_dt  = self.timers[timer]['cpu_dt']
193       sys_dt  = self.timers[timer]['sys_dt']
194       tot_dt  = self.timers[timer]['tot_dt']
195       return cpu_dt, sys_dt, tot_dt
196
197 #-------------------------------------------------------------------------------
198    def StopAndGetTotal(self):
199       """Stop the timer and return total "delta" values.
200       """
201       return self.StopAndGet(self.total_key)
202
203 #-------------------------------------------------------------------------------
204    def StopAll(self):
205       """Stop all timers
206       """
207       lk = self.timers.keys()
208       if self.add_total:
209          lk.remove(self.total_key)
210       for timer in lk:
211          self.Stop(timer)
212
213 #-------------------------------------------------------------------------------
214    def __repr__(self):
215       """Pretty print content of the timer.
216       NB : call automatically StopAll
217       """
218       self.StopAll()
219       if self.add_total:
220          self.Stop(self.total_key)
221       
222       labels = self.fmtstr % self.d_labels
223       out = ['']
224       # get timers list and sort by 'num'
225       lnum = [[val['num'], timer] for timer, val in self.timers.items() if not val['hide']]
226       lnum.sort()
227       if lnum:
228          out.append(self.sepa)
229          if self.add_total and labels:
230             out.append(labels)
231             out.append(self.sepa)
232       for num, timer in lnum:
233          d_info = self.timers[timer].copy()
234          d_info['cpu_sys'] = d_info['cpu_dt'] + d_info['sys_dt']
235          if self.add_total and num == self.MaxNumTimer and len(lnum)>1:
236             out.append(self.sepa)
237          out.append(self.fmtlig % d_info)
238       if lnum:
239          out.append(self.sepa)
240       out.append('')
241       return os.linesep.join(out)
242
243 #-------------------------------------------------------------------------------
244 if __name__ == '__main__':
245    chrono = ASTER_TIMER(format='aster')
246    chrono.Start('Compilation')
247    chrono.Start('CALC_FONCTION')
248    chrono.Start(23, name='CALC_FONCTION')
249    time.sleep(0.4)
250    chrono.Stop('Compilation')
251    chrono.Stop(23)
252    chrono.Start('Child')
253    print chrono