# Time-efficient program

Suppose you are given a program, now you are given a task to minimize
the time, what will be your approach?

and how will you measure the time needed?
I think if we can get total clock cycle by any mean, that could be the
best measure. If so, how can I get that?

2012/8/9 ajay paswan [email protected]:

Suppose you are given a program, now you are given a task to minimize
the time, what will be your approach?

and how will you measure the time needed?
I think if we can get total clock cycle by any mean, that could be the
best measure. If so, how can I get that?

Use Unix’s `time` or equivalent utility.

Then profile (you can do it using ruby-prof gem.)

– Matma R.

On Thu, Aug 9, 2012 at 5:52 PM, ajay paswan [email protected]
wrote:

Suppose you are given a program, now you are given a task to minimize
the time, what will be your approach?

What time?

and how will you measure the time needed?
I think if we can get total clock cycle by any mean, that could be the
best measure. If so, how can I get that?

If you want to measure execution time of a Ruby program there’s
Benchmark.

[email protected]:~\$ irb19 -r benchmark
irb(main):001:0> Benchmark.measure { sleep 1 }
=> 0.000000 0.000000 0.000000 ( 1.000137)

irb(main):002:0> Benchmark.measure { 10_000.times { |i| 10 + i } }
=> 0.000000 0.000000 0.000000 ( 0.001673)

irb(main):003:0> Benchmark.measure { 1000_000.times { |i| 10 + i } }
=> 0.170000 0.000000 0.170000 ( 0.170213)

irb(main):004:0> Benchmark.bm {|x| x.report(“foo”) { sleep 1 }}
user system total real
foo 0.000000 0.000000 0.000000 ( 1.000152)
=> [ 0.000000 0.000000 0.000000 ( 1.000152)
]

http://rubydoc.info/stdlib/benchmark/frames

Kind regards

robert

Then profile (you can do it using ruby-prof gem.)
In the end of the program, the program never halts, I have no clue where
it is lopping, how can i know that? i mean the code block where it is
looping or getting stuck?

On Thu, Aug 9, 2012 at 11:26 PM, ajay paswan [email protected]
wrote:

Then profile (you can do it using ruby-prof gem.)
In the end of the program, the program never halts, I have no clue where
it is lopping, how can i know that? i mean the code block where it is
looping or getting stuck?

You could do poor man’s tracing. Add this at the top:

set_trace_func lambda {|*a| \$stderr.puts a.inspect}

and then invoke

\$ your_program 2>trace.log

Kind regards

robert

To know where the program is looping the simplest way is to put several
“check points”, some actions that should be executed before and after
suspicious code blocks. Those actions can be, for example, message
outputs or outputs of some variables that can cause looping.

Or you can use Ruby IDE that supports debugging where you can walk
through your code one command after another.