Difference between revisions of "Time the execution"
From CodeCodex
(→Ruby) |
(→Ruby) |
||
Line 1: | Line 1: | ||
==Implementations== | ==Implementations== | ||
+ | |||
===Java=== | ===Java=== | ||
− | < | + | <pre class="java"> |
public class ExecutionTimer { | public class ExecutionTimer { | ||
private long start; | private long start; | ||
Line 39: | Line 40: | ||
− | </ | + | </pre> |
See this HowTo to format a duration in ms into a string as "Days , Hours , minutes and seconds". | See this HowTo to format a duration in ms into a string as "Days , Hours , minutes and seconds". | ||
===Ruby=== | ===Ruby=== | ||
− | <pre> | + | <pre class="ruby"> |
class ExecutionTimer | class ExecutionTimer | ||
def initialize | def initialize | ||
Line 50: | Line 51: | ||
def start | def start | ||
@start = Time.now | @start = Time.now | ||
+ | @end = nil | ||
end | end | ||
def end | def end | ||
Line 56: | Line 58: | ||
def duration | def duration | ||
@end - @start | @end - @start | ||
+ | rescue | ||
+ | raise "#{self.class} setup error (start or end)" | ||
end | end | ||
def reset | def reset | ||
Line 64: | Line 68: | ||
t = ExecutionTimer.new | t = ExecutionTimer.new | ||
t.start | t.start | ||
− | 80.times {print "."; sleep 0. | + | 80.times {print "."; sleep 0.01} |
t.end | t.end | ||
puts "\n#{t.duration} sec" | puts "\n#{t.duration} sec" |
Latest revision as of 01:46, 8 March 2011
Implementations[edit]
Java[edit]
public class ExecutionTimer { private long start; private long end; public ExecutionTimer() { reset(); } public void start() { start = System.currentTimeMillis(); } public void end() { end = System.currentTimeMillis(); } public long duration(){ return (end-start); } public void reset() { start = 0; end = 0; } public static void main(String s[]) { // simple example ExecutionTimer t = new ExecutionTimer(); t.start(); for (int i=0; i < 80; i++){ System.out.print(".");} t.end(); System.out.println("\n" + t.duration() + " ms"); } }
See this HowTo to format a duration in ms into a string as "Days , Hours , minutes and seconds".
Ruby[edit]
class ExecutionTimer def initialize reset end def start @start = Time.now @end = nil end def end @end = Time.now end def duration @end - @start rescue raise "#{self.class} setup error (start or end)" end def reset @start = @end = nil end end t = ExecutionTimer.new t.start 80.times {print "."; sleep 0.01} t.end puts "\n#{t.duration} sec"