P55注解

原著:The maximum threads per block are 512, and hence the total number of blocks is calculated by dividing the total number of threads (N) by 512. But if N is not an exact multiple of 512, then N divided by 512 may give a wrong number of blocks, which is one less than the actual count. So, to get the next highest integer value for the number of blocks, 511 is added to N and then it is divided by 512. It is basically the ceil operation on division. 

注解:在C系的语言中,整数的除法操作,a / b,  是不四舍五入的,一概舍掉尾数。例如7 / 3 = 2,余数或者尾数都不要了。这样如果不能整除,(6/3是整除的,得2。但7/3也得2。8/3也得2.直到9/3=3)实际上会稍微造成一点启动CUDA线程总数的问题,例如说,513个总线程,实际上513 / 512 = 1(因为C不要尾数),这样实际上只启动了1个block,里面只有512个线程,那么最后一个线程怎么办?答案是,单独为它其他一个不满的block。也就是说,实际上最常见的代码是这样的:
count = N / 512;
if (N % 512 != 0) //不能整除
    count++;
也就是可以手工判断一次,如果不能整除,+1个block。这是为何这里说的block会少一个的由来。作者没解释。

然后+511又是什么鬼?有一个常见的优化,可以将if优化掉。刚才那个判断可以直接用这样的方式解决:

count = a / b;
if (a % b != 0) count++;
可以被优化成:count = (a + b - 1) / b;

这里的(a + b - 1) / b被叫做整数的快速向上取整优化(见于任何一本计算机学科的《数值计算》课程)。

所以这里的b如果是512的话,就成了:(a + 512 - 1) / 512, 也就是(a + 511) / 512

所以是这样来的。

你可能感兴趣的:(P55注解)