tags:

views:

78

answers:

4

I'm creating a C program to play Gomoku. It uses Minimax search to decide on the best move. However, it can only search for the best move for 10 seconds. How to I determine when my search function has spent 10 seconds searching. If you could provide me with either an example or a link to the documentation that would be much appreciated.

+4  A: 
#include <time.h>
time_t start_time = time(NULL);
while (((int)(time(NULL) - start_time)) < 10) {
  //search
}

That is, what comes to my mind. It is not tested though.

s4ms3milia
glowcoder
A: 

You could use the time() function in time.h. Generally, the returned value is in seconds. Even if it is not, you could simply use difftime() from the same header.

This is a good resource on the necessary functions.

The above link is from a C++ reference site, but that header and examples are all C code.

Kizaru
+1  A: 

You could use the alarm signal. Simply have the signal handler set a global flag called okWereDoneNow and have your search start, check for, and reset it.

The advantage of this over the timer functions is that it requires only a single comparison per iteration of the search. The signal work is expensive, but only run once. In an intensive, presumably-CPU-bound repeated operation, this could be a significant advantage. But don't take my word for it - test!

Thom Smith
A: 

I think your problem is not the time function itself. You mentioned the Minmax Algorithm, which is recursive. The stopping criterion of the Minmax Algorithm is the given search-depth. If you like to have a time-based stopping criterion you should expand your Algorithm with a Iterative Deepening framework and let the recursive Minmax Function return a Sentinel Value, if time is over.

Christian Ammer