4 Copyright (c) 2016 Idiap Research Institute, http://www.idiap.ch/
5 Written by Francois Fleuret <francois.fleuret@idiap.ch>
7 This file is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License version 3 as
9 published by the Free Software Foundation.
11 It is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
14 License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this file. If not, see <http://www.gnu.org/licenses/>.
29 profiler.colors = function(name)
30 if profiler.color then
31 return sys.COLORS[name]
37 function profiler.decorate(model, functionsToDecorate)
39 local functionsToDecorate = functionsToDecorate or
45 for _, name in pairs(functionsToDecorate) do
48 -- We decorate the class and not the object, otherwise we cannot
49 -- save models anymore.
51 if rawget(model, name) then
52 error('We decorate the classes, not the objects, and there is a `'
58 local toDecorate = model
60 while not rawget(toDecorate, name) do
61 toDecorate = getmetatable(toDecorate)
64 local nameOrig = name .. '__orig'
66 if not toDecorate[nameOrig] then
67 -- print('Decorating ' .. toDecorate.__typename .. '.' .. name)
68 toDecorate[nameOrig] = toDecorate[name]
69 toDecorate[name] = function(self, ...)
70 local startTime = sys.clock()
71 local result = { self[nameOrig](self, unpack({...})) }
72 local endTime = sys.clock()
73 self.accTime[name] = (self.accTime[name] or 0) + endTime - startTime
80 if torch.isTypeOf(model, nn.Container) then
81 for _, m in ipairs(model.modules) do
82 profiler.decorate(m, functionsToDecorate)
88 function profiler.timingString(l, t, nbSamples, totalTime)
91 s = string.format('%s %.02fs %s[%.02f%%]',
93 profiler.colors('blue'),
98 s = s .. string.format(profiler.colors('green') .. ' (%.01fmus/sample)',
102 s = s .. profiler.colors('black')
107 function profiler.print(model, nbSamples, totalTime, indent)
108 local indent = indent or ''
111 if not model.accTime then
112 error('The model does not seem decorated for profiling.')
116 for _, t in pairs(model.accTime) do
117 localTotal = localTotal + t
120 totalTime = totalTime or localTotal
122 if torch.isTypeOf(model, nn.Container) then
125 if profiler.color then
130 hint = hint .. profiler.colors('red')
133 print(profiler.timingString(indent .. hint .. ' ' .. model.__typename,
134 localTotal, nbSamples, totalTime))
136 for l, t in pairs(model.accTime) do
137 print(profiler.timingString(indent .. ' :' .. l, t, nbSamples, totalTime))
142 if torch.isTypeOf(model, nn.Container) then
143 for _, m in ipairs(model.modules) do
144 profiler.print(m, nbSamples, totalTime, indent .. ' ')