任务平均分配的小算法

如:进程池个数为7,需要完成的任务为54,如果用满进程池,有以下几种简单的分法:

7  7  7  7  7  7  12

8  8  8  8  8  8  6

8  8  8  8  8  7  7

 

第三种分法最平均:

54  7

54=(8*5)+(7*2)

7=54/7

8=7+1

5=54%7

2=7-5

 

python 实现:

#!usr/bin/env python
#encoding=utf-8

def division(sum, num):
    remainder = sum % num
    quotient = sum / num
    result = []

    for i in range(remainder):
        result.append(quotient + 1)

    for i in range(num - remainder):
        result.append(quotient)

    print result

    start = 0
    result_start_end = []
    for i in range(num):
        end = start + result[i]
        result_start_end.append([start, end])
        start = end

    return result_start_end

if __name__ == '__main__':
    print division(54, 7)

结果:

[8, 8, 8, 8, 8, 7, 7]
[[0, 8], [8, 16], [16, 24], [24, 32], [32, 40], [40, 47], [47, 54]]

 

原文:http://www.cnblogs.com/congbo/archive/2012/08/27/python.html

posted @ 2012-08-27 21:40  congbo  阅读(3790)  评论(0编辑  收藏  举报