tags:

views:

84

answers:

2

Hi, how can I limit the execution time of my iterate-deepening search without using a thread?

Currently I use this simple implementation, but it is not efficient and sometimes even does not terminate within the given timeframe..

timer.Start();
best = doSearch();
timer.Stop();
dpuble time = timer.Duration;
while (time*1000 < 400)
{
   timer.Start();
   best = doSearch();
   timer.Stop();
   time += timer.Duration;
}
+2  A: 

If you want to avoid threading, you would need to pass a timestamp into your doSearch() method. It could (periodically) check the current time, and if the duration is past some threshold, raise an exception or return the failed case.

Reed Copsey
A: 

How do you want to terminate execution? Do you want to exit the program, or just stop searching? If you're okay with destroying your process, you could do this:

 var timer = new Timer(new TimeSpan(0, 0, 400));
 timer.Elapsed += { throw new Exception("Time's up!"); }
 timer.Start();
 doSearch();
 timer.Stop();

But I think you want something more reasonable. In that case, you probably have to do this within doSearch itself. I assume that the method is iterative or recursive, in which case you can store the start time in an instance variable, then check the elapsed time at a well-known point in the iteration/recursion. For example:

private DateTime _start;
private TimeSpan _maxTime = new TimeSpan(0, 0, 400);

public void TimedSearch()
{
    _start = DateTime.Now;
    DoSearch();
}

public void DoSearch()
{
    while (notFound)
    {
        if (DateTime.Now - _start > _maxTime)
            return;

        // search code
    }
}
JSBangs
These two approaches could be combined into what I think would be the best solution. `private volatile bool timesUp` could be set to true by the `timer.Elapsed` method, and `DoSearch()` could periodically check this value.
Jeffrey L Whitledge
how can I set timesUp with timer.Elapsed?
BeatMe
@BeatMe: `timer.Elapsed += { this.timesUp = true; };`
JSBangs