This site requires JavaScript, please enable it in your browser!
Greenfoot back
Zamoht
Zamoht wrote ...

2013/10/26

Calculations and efficiency

Zamoht Zamoht

2013/10/26

#
I've done some testing in one of my scenarios and something bothers me. I have this method in my code which calculates where my actor should be placed:
public void setCrossLocation(int x, int y)
    {
        crossX = x;
        crossY = y;
        setLocation(x * getWorld().tileSize, y * getWorld().tileSize + getWorld().tileSize * getWorld().getTopOffset());
    }
What bothers me is that this method takes 4-5 ms to execute. Is it normal that "simple" calculations like these take so long to complete? Is there any way I can optimize it?
danpost danpost

2013/10/26

#
Well, one thing you could do is to reduce the number of method calls with:
public void setCrossLocation(int x, int y)
{
    crossX = x;
    crossY = y;
    World world = getWorld(); // so you only get the world once
    int tSize = world.tileSize; // making the value locally accessible
    setLocation(x*tSize, (y+world.getTopOffset())*tSize);
}
Please post back as to what savings you get, if any. BTW, the last line with 'getTopOffset' will need the world typecast to your subclass of world. It is hard to say whether line 6 is necessary or not. You had getWorld().tileSize returned three times and I reduced it to two uses by the summing of 'y' and 'getWorld().getTopOffset()' before multiplying by it. It may be faster (now) to remove 6 and use 'world.tileSize' for the two times I used it (which would eliminate the need to set up another local field).
Zamoht Zamoht

2013/10/26

#
I changed the method but it still prints out 4-5 ms. Here is the code:
    public void setCrossLocation(int x, int y)
    {
        SimpleTimer timer = new SimpleTimer();
        timer.mark();
        crossX = x;
        crossY = y;
        TowerWorld world = getWorld();
        int tSize = world.tileSize;
        setLocation(x * tSize, (y + world.getTopOffset()) * tSize);
        timer.print();
        Greenfoot.stop();
    }
    public int getTopOffset()
    {
        return 1;
    }
The SimpleTimer is imported from Greenfoot and I added the print method:
    public void print()
    {
        System.out.println(""+millisElapsed());
    }
Zamoht Zamoht

2013/10/26

#
I am so sorry for wasting your time today. I don't know what it is maybe I should just get some sleep. It had nothing to do with the calculations.
You need to login to post a reply.