我在联合中使用匿名结构来快速获得 a%b。
你知道任何其他方法来获得 a%b 而不使用 b 的 2 的幂。
包括清单:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
和工会宣言:
//C99
//my first program to test rand() for any periodicity
union //for array indexing without modulus operator
{
unsigned int counter; //32 bit on my computer
struct
{
unsigned int lsb:16; //16 bit
unsigned int msb:16; //16 bit
};
struct
{
unsigned int bit[32];
};
} modulo;
union // for rand()%256
{
unsigned int randoom; //from rand()
struct
{
unsigned int lsb:5;//equivalent to rand()%32 without any calculations
unsigned int msb:27;
};
}random_modulus;
这里是主要功能:
int main()
{
srand(time(0));
modulo.counter=0;//init of for-loop counter
// i am takin (counter%65536) for my array index which is modulus.lsb
unsigned int array_1[65536];
float array_mean=0,delta_square=0;
clock_t clock_refe;
//taking counter%65536 using lsb (2x faster)
clock_refe=clock();
for(;modulo.counter<1000000000;modulo.counter++)
{
// i need accumulated randoms for later use for some std. dev. thing.
random_modulus.randoom=rand();
array_1[modulo.lsb]+=random_modulus.lsb;
}
//getting average clock cycles
for(int i=0;i<65536;i++)
{
array_mean+=array_1[i];
}
array_mean/=65536.0f;
//getting square of deltas
float array_2[65536];
for(int i=0;i<65536;i++)
{
array_2[i]=(array_1[i]-array_mean)*(array_1[i]-array_mean);
}
//horizontal histogram for resoluton of 20 elements
for(int i=0;i<65536;i+=(65536)/20)
{
for(int j=0;j<(array_2[i]*0.01);j++)
{
printf("*");
}
printf("\n");
}
//calculations continue .....
return 0;
}
某些数组中的预先计算的值可能吗?但是如果我只使用一次 % calc 部分,这是一样的。你能提供一些关于按位操作手册的书籍参考吗?