最适合的记忆分配

时间:2014-03-14 16:12:42

标签: c#

我正在尝试实现最佳匹配内存分配。我已经完成了代码,我认为应该可以工作但不知何故它似乎陷入了循环。我无法弄清楚原因。以下是我的代码。我想以最少的内存浪​​费将作业分配到内存中。

public void bestFit(int job_size)
{
    string str1 = "";
    string str2 = "";
    string str3 = "";
    int memory_block = 99999;
    int subscript = 0;
    int initial_memory_waste = memory_block - job_array[0];
    int job_counter = 0;
    int counter = 1;
    int memory_waste = 0;
    while (counter <= memory_array.Length)
    {
        if (job_size > memory_array[counter - 1])
        {
            counter += 1;
        }
        else
            memory_waste = memory_array[counter - 1] - job_size;
        {
            if (initial_memory_waste > memory_waste)
            {
                subscript = counter;
                initial_memory_waste = memory_waste;
                counter += 1;
            }
        }
    }

    queued_jobs = counter;
    str3 = ("Job number: " + (queued_jobs).ToString() + " of size: " + job_size.ToString());
    if (job_counter < job_array.Length)
    {
        bf_waiting_queue.Add(str3);
    }
    else
    {
        str1 = ("Job number: " + (job_counter).ToString() + " of size: " + job_size.ToString() + " is allocated to Memory block: " + (subscript).ToString() + " of size: " + memory_array[subscript - 1]).ToString();
        memory_waste = memory_array[subscript - 1] - job_size;
        str2 = ("Memory waste is: " + memory_waste.ToString());
        bf_total_memory_waste += memory_waste;
        memory_array[counter - 1] = (memory_array[counter - 1] - job_size);
        bf_jobsInMemory.Add(str1 + "\t" + str2);
        job_counter += 1;
        counter = 1;
    }
} 

1 个答案:

答案 0 :(得分:3)

除了其他人指出的大括号问题之外,你的逻辑使你可以从不增加'计数器',这就是你陷入循环的原因。以下重组更清晰,并保证您始终增加'计数器'。此外,一些评论也不会受到影响。

while (counter <= memory_array.Length)
{
    // If block fits, consider it
    if (job_size <= memory_array[counter - 1])
    {
        memory_waste = memory_array[counter - 1] - job_size;

        // If this block is less wasteful, remember it
        if (initial_memory_waste > memory_waste)
        {
            subscript = counter;
            initial_memory_waste = memory_waste;
        }
    }

    // Next block
    counter += 1;
}