最佳内存分配

本文关键字:分配 内存 最佳 | 更新日期: 2023-09-27 17:50:14

我正在努力实现最适合的内存分配。我已经做了代码,我认为应该工作,但不知何故,它似乎陷入了循环。我不知道为什么。以下是我的代码。我想把作业分配到内存浪费最少的内存

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;
    }
} 

最佳内存分配

除了其他人指出的大括号问题外,您的逻辑使永远不能增加'counter'成为可能,这就是为什么您陷入循环。下面的重组更清晰,并保证您总是增加'counter'。另外,几句评论也无妨。

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;
}