我有一个类似这样的数组:
{
1, 2, 3, 4,
5, 6, 7, 8,
9,10,11,12,
13,14,15,16
}我需要像1,2,3,4, 8,7,6,5, 9...一样,以一种锯齿状的方式来迭代它。
这很简单,但是开销的空间很小,所以我需要它尽可能的节省时间。每一个额外的周期在这里都很重要。
这就是我现在拥有的:
#define send_colors_zigzag(io, colorz, width, height) do { \
for(int8_t y = 0, uu=0, a=1; y < (height); y++, uu+=width, a *= -1) { \
uint8_t uup = uu + (a < 0 ? width : 0); \
for(uint8_t x = 0; x < (width); x++) { \
uint8_t pos = uup + a*x; \
const color_t clr = (colorz)[pos]; \
send_one_color(io_pack(io), clr); \
} \
} \
} while(0)send_one_color是一个宏,它扩展为单个位的循环,我不想在这个宏中重复两次(需要保持它很小)。
我有理由这样做,作为一个宏,io和io_pack是一些魔术的引脚混叠,这是不能用一个常规的函数。
我相信它循环正确,但它不够快(所以不能使用)。
我正在研制一台8位微型16兆赫的手机。
对于信息,这个版本可以工作(但是大的内部宏重复了两次,我想避免):
#define send_colors_zigzag(io, colorz, width, height) do { \
int8_t x; \
for(int8_t y = 0; y < (height); y++) { \
for(x = 0; x < (width); x++) { \
send_one_color(io_pack(io), (colorz)[y*width + x]); \
} \
y++; \
for(x = width-1; x >=0; x--) { \
send_one_color(io_pack(io), (colorz)[y*width + x]); \
} \
} \
} while(0)发布于 2015-03-22 13:47:32
这是一种避免尽可能多的算术的方法,特别是在内部循环中。
color_t* p = (colorz);
for (int8_t y = 0; y < (height); y++) {
int8_t inc = y & 1 ? -1 : 1;
if (y) {
p += (width) + inc;
}
for (int8_t x = 0; x < (width); x++) {
send_one_color(io_pack(io), *p);
p += inc;
}
}如果height为偶数,或者您不介意未定义的行为(因为p点超出了colorz的末尾),则可以使用此变体保存几个周期:
color_t* p = (colorz);
for (int8_t y = 0; y < (height); y++) {
int8_t inc = y & 1 ? -1 : 1;
for (int8_t x = 0; x < (width); x++) {
send_one_color(io_pack(io), *p);
p += inc;
}
p += (width) - inc;
}https://stackoverflow.com/questions/29193419
复制相似问题