classdef Timer % Handy timer class to start and stop mutliple timer in parallel. % % It's basically a linked list with the timers' starting timestamp % stored in the data. % % Timer does not need to be instanciated. Simply use its start() and % stop() static methods. % % example: % % Timer.start(); % % run some code here % Timer.stop() % % will return the running time between the two Timer's methods call. % % example: % % timer1 = Timer.start(); % % run some code here % timer2 = Timer.start(); % % run some other code here % Timer.stop(timer2); % % run some other code here % Timer.stop(timer1) % % Stop the timers when wanted. If no argument is given to Timer.stop() % it will return the running time between Timer.stop() and the % last time Timer.start() has been called. % % The Timer.format property is not used yet but it would be a nice % feature. properties (Constant, Hidden = true) data = LinkedList; format = struct('string','%sh %sm %ss %sms'); end methods (Static) function output = start output = Timer.data.append(datetime('now')); end function output = stop(varargin) if (Timer.data.length == 0) error('There is no timer currently running.'); end if (nargin == 1) assert(ischar(varargin{1}),'The ID of a timer must be a char array.'); timerStartTime = Timer.data.pop(varargin{1}); else timerStartTime = Timer.data.pop; end output = Timer.getElapsedTime(datetime('now')-timerStartTime); end function clearAll Timer.data.clear; end end methods (Static, Hidden = true) function output = getElapsedTime(duration) elapsedTime = split(char(duration),':'); elapsedMilliseconds = Timer.getElapsedMilliseconds(duration); output = [elapsedTime{1} ' hours ',... elapsedTime{2} ' minutes ',... elapsedTime{3} ' seconds ',... elapsedMilliseconds ' milliseconds']; output = sprintf(Timer.format.string,elapsedTime{1},elapsedTime{2},elapsedTime{3},elapsedMilliseconds); end function output = getElapsedMilliseconds(duration) durationInSeconds = num2str(seconds(duration)); output = extractAfter(durationInSeconds,'.'); if isempty(output); output = '000'; end end end end