当前位置:网站首页>【C语言指针】用指针提升数组的运算效率
【C语言指针】用指针提升数组的运算效率
2022-08-05 10:28:00 【SN-Grotesque】
原本代码
static void test()
{
size_t size = 500 * pow(1024, 2);
uint8_t *data = (uint8_t *)malloc(size);
size_t x;
clock_t start, end;
start = clock();
for(x = 0; x < size; ++x) {
data[x] = 0x41;
}
end = clock();
printf("%lf seconds\n",(double)(end - start) / CLOCKS_PER_SEC);
}
经过十次的执行,取平均值为1.9628秒
修改后代码
static void test()
{
size_t size = 500 * pow(1024, 2);
uint8_t *data = (uint8_t *)malloc(size);
size_t x;
clock_t start, end;
start = clock();
for(x = 0; x < size; ++x) {
*data = 0x41;
data++;
}
end = clock();
printf("%f seconds\n",(double)(end - start) / CLOCKS_PER_SEC);
}
经过十次执行,取平均值为1.8914秒
可以看到平均下来指针比使用下标的方式要快上近
0.1秒,你可能会说就100毫秒有啥好优化的。
那是因为你接触到的项目不够大,如果在一个大型项目上面还是只使用数组下标的话,就比较容易导致整个项目的节奏被某些函数或运算给拖后腿。
最后如果你是一个不够了解指针或C语言的人可能会注意到一个现象。
那就是后续使用printf函数无法输出上面这个data变量,输出结果是什么也没有。
那是因为指针已经指向了这个变量的最后一个值的下一个值。
简单来说就是p = data[(n - 1) + 1];
p是指针指向的值,n是变量长度。
要解决这个问题只需要使用另一个指针来在一开始指向这个data变量,然后后续的运算都用此新指针。
边栏推荐
- 项目成本控制如何帮助项目成功?
- Common operations of oracle under linux and daily accumulation of knowledge points (functions, timed tasks)
- GCC编译的时候头文件搜索规则
- [Strong Net Cup 2022] WP-UM
- 第四章:redis 数组结构的set和一些通用命令「建议收藏」
- 第五章:多线程通信—wait和notify
- 语音社交软件开发——充分发挥其价值
- 2022 Huashu Cup Mathematical Modeling Question A Optimization Design Ideas for Ring Oscillators Code Sharing
- static linking and dynamic linking
- 用户考试分数大于单科科目平均分的查询
猜你喜欢

012_SSS_ Improving Diffusion Model Efficiency Through Patching

STM32+ULN2003驱动28BYJ4步进电机(根据圈数正转、反转)

教你本地编译运行一个IDEA插件,在IDEA里聊天、下棋、斗地主!

NowCoderTOP35-40 - continuous update ing

Opencv算术操作

登录功能和退出功能(瑞吉外卖)

【MindSpore易点通机器人-01】你也许见过很多知识问答机器人,但这个有点不一样

Meteorological data processing example - matlab string cutting matching and R language date matching (data splicing)

字节一面:TCP 和 UDP 可以使用同一个端口吗?

Huawei's lightweight neural network architecture GhostNet has been upgraded again, and G-GhostNet (IJCV22) has shown its talents on the GPU
随机推荐
Meteorological data processing example - matlab string cutting matching and R language date matching (data splicing)
基于MindSpore高效完成图像分割,实现Dice!
js劫持数组push方法
【Unity】【UGUI】【在屏幕上显示文本】
2022 Huashu Cup Mathematical Modeling Question A Optimization Design Ideas for Ring Oscillators Code Sharing
第五章:activiti流程分流判断,判断走不同的任务节点
Technical dry goods | Hausdorff distance for image segmentation based on MindSpore
技术干货 | 基于 MindSpore 实现图像分割之豪斯多夫距离
Create a Dapp, why choose Polkadot?
开发常用手册链接分享
Introduction to SD NAND Flash!
【 temperature warning program DE development 】 event driven model instance
How does the official account operate and maintain?Public account operation and maintenance professional team
R语言使用yardstick包的pr_curve函数评估多分类(Multiclass)模型的性能、查看模型在多分类每个分类上的ROC曲线(precision(精准率),R代表的是recall(召回率)
What are the standards for electrical engineering
Go编译原理系列6(类型检查)
化繁为简!阿里新产亿级流量系统设计核心原理高级笔记(终极版)
MySQL data view
three.js debugging tool dat.gui use
教你本地编译运行一个IDEA插件,在IDEA里聊天、下棋、斗地主!