Hi all,
I am trying to optimize a piece of code I wrote. I have a loop that iterates for, let's say, 100 iterations. I found that two functions consume most of the time, and I try to understand why and could I optimize them.To get a basic look, I called next just before the first function and timed the loop, than called next just before the second function and timed again, and finally called next just after the second function and timed the loop again.
Indeed, it seems that these two functions take the most time and the rest of the loop body is OK.
I started with the first function. Tried a next just before the call and jut after the call, so the difference is just the call itself. When the next is just before - I time 9 seconds per 50 loop iterations. When the next is just after - I time 28 seconds per 50 iterations.
The function itself is quite simple - it gets 3 scalars (one of which is a field of some object), checks a couple of if's on the values and some basic math (including modulo %), and returns an array with a couple of hashes, each with two numerical fields. That's it.
I tried to "delete" the function body just to make sure where the problem is, so I added return []; as the first line of the function. Now timing it with a next just after the function call I get 1 seconds per 50 iterations. Obviously better than the 28 seconds, but still significantly higher than the 9 seconds I got with next just before the call, and the function does absolutely nothing! i even tried to replace the variables with which the function is called, to make sure the problem is not in evaluating them, so I replaced them with hard-coded numbers -- still 11 seconds.
This is obviously the very beginning - just understanding 2 out of the 28 seconds I wish to reduce, but I'm already stuck here.
as always, your help and wise word will be greatly appreciated.
Thanks!
In reply to Some code optimization by roibrodo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |