开发者

Limiting Thread Execution Processor Cycles in Java

I'm writing an AI-testing Framework for a competition. Participants submit a Bot class which matches a given Interface. Then all the bots play a turn-based game. On every turn, I want to do the following:

For every bot B:
    start a thread that runs at most N cycles and does B.getNextMove()
wait for all threads to complete
Make all moves开发者_如何转开发 (from each bot).

My difficulty comes in saying "at most N cycles". I can limit all the bots by time (say half a second per turn) but this means that some can get more processor cycles than others and doesn't permit a strict "your bot should be able to make its decision re: a turn in X time" requirement in the competition.

As stated, this is in Java. Any ideas? I've been looking at concurrency and locking but this doesn't feel like the right direction. Also, it's possible to not run the bots in Parralel and then use time for the restriction (given that the computer isn't running anything else at the time), but this would be undesirable as it would significantly slow down the speed at which we could have results from the games.


I'd make an interface with the bot to have them do 1 iteration of their algorithm,and do a simple count.

If you need hard time/cpu limits there arn't that many(easy) ways to manage that in java.

You can't measure cpu cycles with java, but you can measure CPU time - which is a vast improvement over using just wall clock time.

To get the cpu time of the current thread you'd use (from the standard java.lang.management package)

ThreadMXBean tm = ManagementFactory.getThreadMXBean();
long cpuTime = tm.getCurrentThreadCpuTime();


Since you're controlling the bot execution and explicitly calling next yourself, why not just count the iterations? e.g.

public class Botcaller extends Thread 
{
  private Bot bot;
  int cycles_completed;
  public static final int MAX_ALLOWED_CYCLES=...;
  public void run()
  {
     while (cycles_completed <MAX_ALLOWED_CYCLES)
     {
       bot.move;
       cycles_completed++;
       yield()
     }
  }
}


I think it will be very difficult to control threads at this low a level from Java. I no of know way to stop a thread safely that is running.

Another option is to let each bot run in whatever time it wants. Have one thread per bot but poll the location in a master thread every second. If they haven't updated location in that "round" then they miss out and have to wait for the next one. Make sure that the world state that each bot sees is the one controlled by the master thread.

The nice thing about this approach is that it lets bots sacrifice rounds if they want to do something more complicated.


I think Robocode does something similar... you may want to look there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜