具有定时条件的while循环不会终止

时间:2014-02-02 12:11:01

标签: c++ time struct while-loop initialization

我正在做涉及本地搜索的作业问题。我想在一段时间后使用新的初始状态重新开始搜索。为此我在while循环中包含了一个时间条件。

void run_local_search()
{
    while (time(NULL) - timer < (tim * 60) - 1) // tim is some user defined time in minutes. I've initialized timer in my main function right before calling the run_local_search().
    {
        struct state initial; // Declaring the initial state structure

        start_state(&initial); // Generates a random starting state.
        if (initial.profit > best.profit)
        {
            best = initial;
        }
        local_search(&initial);
    }
}

我的主要本地搜索功能是

void local_search(state* s)
{
    clock_t searchtime; 
    searchtime = clock(); // I initialize the clock right before the search loop here
    while ((clock() - searchtime)/CLOCKS_PER_SEC < 2) // I want the loop to run for 2 seconds
    {...}
    cout << "Done" << endl;
}

我发现结构状态初始化;语句不会在while循环的迭代中重新初始化初始结构。初始化的相同值在while循环的新迭代中进行,因此生成随机值的start_state函数变得无用!我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

根据您提供的小信息,我可以猜测算法将被初始化一次,之前蒂姆分钟循环:

void run_local_search(){
  struct state initial;
  //     start_state(&initial);   //moved into loop
  while (time(NULL) - timer < (tim * 60) - 1){
    start_state(&initial);
    if (initial.profit > best.profit){
        best = initial;
    }
    local_search(&initial);
  }
}