测试100M(1亿)个元素的初始化时间长度作为效率对比参考值。CPU: Intel i5@2.90GHZ

最后封装一个优化后的自定义双字节memset函数。

typedef unsigned char      uint8_t;
typedef unsigned short     uint16_t;
typedef unsigned int       uint32_t;
typedef unsigned long long uint64_t;

#define MAX_SIZE (1024*1024*100)  //100MiByte
uint8_t pBuff[MAX_SIZE] = { 0 };
      
    uint64_t len = MAX_SIZE;
    uint16_t value = 0x1234;    
    uint8_t ch_High = value >> 8;
    uint8_t ch_Low  = value&0xFF;
  
    //测试1:传统for运行耗时47ms  
    for (uint64_t i = 0; i < len/2; i++)
    {
       pBuff[i] = ch_High;
       pBuff[i+1] = ch_Low;
    }
    //测试2:指针for运行耗时31ms  
    uint8_t* pt = pBuff;
    for (uint64_t i = 0; i < len/2; i ++ )
    {
        *(uint16_t*)pt = value;
        pt += 2;
     }

//通过以上测试可以看出用指针赋值比传统数组赋值快51%
//故有优化后的my_memset函数,用于初始化双字节函数。

void my_memset(uint8_t *buf,uint16_t value,uint64_t len)
{
    for (uint64_t i = 0; i < len/2; i ++)
    {
        *(uint16_t*)buf = value;//关键:指针类型的转换
        buf += 2;
    }   
}


//整体测试使用
void main()
{
    uint8_t testData[10] = { 0 };

    my_memset(testData, 0x1234, sizeof(testData));

    for (size_t i = 0; i < sizeof(testData); i++)
    {
        printf("%02x ",testData[i]);
    }
}

//最终输出:34 12 34 12 34 12 34 12 34 12
08-10 10:15