当前位置:网站首页>【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变量,然后后续的运算都用此新指针。
边栏推荐
- 数据可视化(一)
- 一个栈的输入序列为1 2 3 4 5 的出站顺序的理解
- Complete image segmentation efficiently based on MindSpore and realize Dice!
- 第四章:redis 数组结构的set和一些通用命令「建议收藏」
- Common operations of oracle under linux and daily accumulation of knowledge points (functions, timed tasks)
- 攻防世界-PWN-new_easypwn
- [Strong Net Cup 2022] WP-UM
- FPGA:开发环境Vivado的使用
- uniapp 连接ibeacon
- js hijacks the array push method
猜你喜欢

What is SPL?

Jenkins manual (2) - software configuration

【 temperature warning program DE development 】 event driven model instance

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

这份阿里强推的并发编程知识点笔记,将是你拿大厂offer的突破口

three.js debugging tool dat.gui use

60行从零开始自己动手写FutureTask是什么体验?

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

阿里顶级架构师多年总结的JVM宝典,哪里不会查哪里!

还在找网盘资源吗?快点收藏如下几个值得收藏的网盘资源搜索神器吧!
随机推荐
第六章:activiti流程分流判断之排它网关和并行网关
RT - Thread record (a, RT, RT Thread version - Thread Studio development environment and cooperate CubeMX quick-and-dirty)
第三章 : redis数据结构种类
化繁为简!阿里新产亿级流量系统设计核心原理高级笔记(终极版)
Is digital transformation a business buy-in?
MySQL data view
Offensive World-PWN-new_easypwn
SD NAND Flash简介!
第五章:activiti流程分流判断,判断走不同的任务节点
SQL外连接之交集、并集、差集查询
技术干货 | 基于 MindSpore 实现图像分割之豪斯多夫距离
LeetCode 216. Combined Sum III (2022.08.04)
MySQL之数据视图
上位机开发C#语言:模拟STC串口助手接收单片机发送数据
电气工程的标准是什么
uniapp connect ibeacon
Opencv图像缩放和平移
three objects are arranged in a spherical shape around the circumference
第五章:多线程通信—wait和notify
JS introduction to reverse the recycling business network of learning, simple encryption mobile phone number