优化这段代码if(uint32_t i = 0; i < totalBox) { int ret; uint8_t UDP_buff[34] = {0}; pt1.x= detectData[totalBox * TOPLEFTX + i] * widthScale; pt1.y= detectData[totalBox * TOPLEFTY + i] * heightScale; pt2.x= detectData[totalBox * BOTTOMRIGHTX + i] * widthScale; pt2.y= detectData[totalBox * BOTTOMRIGHTY + i] * heightScale; printf("********************%d %d %d %d \n", pt1.x, pt1.y,pt2.x, pt2.y); UDP_buff[16] = 0x12; UDP_buff[18] = (pt1.x + (pt2.x - pt1.x)/2) * 100; UDP_buff[19] = (pt1.y + (pt2.y - pt1.y)/2) * 100; uint16_t tem = CalculateCrc16(&UDP_buff[8],24); UDP_buff[32] = tem; UDP_buff[33] = tem >> 8; // printf("************tem == %d\r\n",tem); ret = UDP_send(sockfd,"192.168.1.121",2339,(char *)UDP_buff,34); if(!ret) { printf("UDP Failed to send packets(cmd:%d); streamDescSize = %d !!! \r\n",ret,34); } usleep(500); }
时间: 2024-01-17 18:15:15 浏览: 46
可以尝试优化如下:
1.将`totalBox`的类型改为`uint32_t`,避免在循环中的类型转换操作。
2.将计算量大的表达式`detectData[totalBox * TOPLEFTX + i] * widthScale`等提取出来,减少重复计算。
3.使用`snprintf`代替`printf`,避免在循环中使用较慢的标准输出函数。
4.将`UDP_buff`的大小改为常量,避免在循环中重复分配和释放内存。
优化后的代码如下:
```c++
const uint32_t UDP_BUFF_SIZE = 34;
char UDP_buff[UDP_BUFF_SIZE] = {0};
for (uint32_t i = 0; i < totalBox; ++i) {
int ret;
uint32_t baseIndex = totalBox * i;
float tlx = detectData[baseIndex + TOPLEFTX];
float tly = detectData[baseIndex + TOPLEFTY];
float brx = detectData[baseIndex + BOTTOMRIGHTX];
float bry = detectData[baseIndex + BOTTOMRIGHTY];
pt1.x = tlx * widthScale;
pt1.y = tly * heightScale;
pt2.x = brx * widthScale;
pt2.y = bry * heightScale;
printf("********************%d %d %d %d \n", pt1.x, pt1.y,pt2.x, pt2.y);
UDP_buff[16] = 0x12;
int centerX = (pt1.x + (pt2.x - pt1.x)/2) * 100;
int centerY = (pt1.y + (pt2.y - pt1.y)/2) * 100;
UDP_buff[18] = centerX;
UDP_buff[19] = centerY;
uint16_t crc = CalculateCrc16(&UDP_buff[8], 24);
UDP_buff[32] = crc;
UDP_buff[33] = crc >> 8;
char ip[16];
snprintf(ip, sizeof(ip), "192.168.1.121");
ret = UDP_send(sockfd, ip, 2339, (char *)UDP_buff, UDP_BUFF_SIZE);
if (!ret) {
printf("UDP Failed to send packets(cmd:%d); streamDescSize = %d !!! \r\n", ret, UDP_BUFF_SIZE);
}
usleep(500);
}
```
阅读全文