测试1G元素的初始化时间长度作为效率对比参考值。
最后封装一个优化后的自定义双字节memset函数。
#include <stdio.h>
#include <stdint.h>
#include <time.h>
//一般32位的编译器,静态数据区只分配大约2g的内存
#define MAX_SIZE (1024*1024*1024) //1024MiByte=1GByte
uint8_t pBuff[MAX_SIZE] = { 0 };
int main()
{
clock_t start, end;
double seconds = 0;
uint64_t len = MAX_SIZE;
uint16_t value = 0x1234;
uint8_t ch_High = value >> 8;
uint8_t ch_Low = value & 0xFF;
printf("Exam MAX_SIZE=0x%lx.\n", MAX_SIZE);
//测试1:传统for运行耗时0.374
start = clock();
for (uint64_t i = 0; i < (len / 2); i++)
{
pBuff[i] = ch_High;
pBuff[i + 1] = ch_Low;
}
end = clock();
seconds = (double)(end - start) / CLOCKS_PER_SEC;
printf("Use time1: %.8fs \n", seconds);
//测试2:指针for运行耗时0.256
uint8_t* pt = pBuff;
start = clock();
for (uint64_t i = 0; i < (len / 2); i++)
{
*(uint16_t*)pt = value;
pt += 2;

文章比较了100M元素数组初始化的传统for循环与指针for循环的效率,提出并实现了一个优化的my_memset函数,利用指针类型转换提高初始化速度。
最低0.47元/天 解锁文章
1651

被折叠的 条评论
为什么被折叠?



