[英]Fast implementation binary exponentiation implementation in OpenCL
我一直在嘗試在OpenCL中設計一個快速二進制求冪實現。 我目前的實現與本書中關於pi的實現非常類似。
// Returns 16^n mod ak
inline double expm (long n, double ak)
{
double r = 16.0;
long nt;
if (ak == 1) return 0.;
if (n == 0) return 1;
if (n == 1) return fmod(16.0, ak);
for (nt=1; nt <= n; nt <<=1);
nt >>= 2;
do
{
r = fmod(r*r, ak);
if ((n & nt) != 0)
r = fmod(16.0*r, ak);
nt >>= 1;
} while (nt != 0);
return r;
}
還有改進的余地嗎? 現在我的程序花費了大部分時間在這個功能上。
我的第一個想法是對它進行矢量化,潛在的速度可達~1.6倍。 每循環使用5次乘法,而原始使用2次乘,但是對於足夠大的N,循環次數大約為四分之一。將所有double
s轉換為long
s,並且為%
s換出fmod
可以提供一些速度取決於使用的確切GPU和任何。
inline double expm(long n, double ak) {
double4 r = (1.0, 1.0, 1.0, 1.0);
long4 ns = n & (0x1111111111111111, 0x2222222222222222, 0x4444444444444444,
0x8888888888888888);
long nt;
if(ak == 1) return 0.;
for(nt=15; nt<n; nt<<=4); //This can probably be vectorized somehow as well.
do {
double4 tmp = r*r;
tmp = tmp*tmp;
tmp = tmp*tmp;
r = fmod(tmp*tmp, ak); //Raise it to the 16th power,
//same as multiplying the exponent
//(of the result) by 16, same as
//bitshifting the exponent to the right 4 bits.
r = select(fmod(r*(16.0,256.0,65536.0, 4294967296.0), ak), r, (ns & nt) - 1);
nt >>= 4;
} while(nt != 0); //Process n four bits at a time.
return fmod(r.x*r.y*r.z*r.w, ak); //And then combine all of them.
}
編輯:我很確定它現在有效。
nt = log2(n);
的循環nt = log2(n);
可以替換為 if (n & 1) ...; n >>= 1;
r = 16;
,fmod(r * r,ak)vs fmod(16 * r,ak)可以很容易地延遲,只計算每第N次迭代的模數 - 循環展開?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.