快讯资讯
手机优化
系统数码
网络通信人工智能
网站游戏
测评专题

  CPU 迎来高光时刻:解读       电力需求迎来巅峰,智算    

程序跑得慢,不一定是算法问题:可能是 CPU 缓存

时间:2026-09-10 22:48 来源:未知 人气:

哈喽,大家好,我是呼噜噜,之前的系列文章我们分别介绍了 CPU Cache 的基本概念、组织架构以及缓存一致性协议

知其然还要知其所以然,但对开发者来说,最关键的还是如何把这些底层原理变成写出高性能代码的

今天我们就从几个实打实的经典代码案例切入,聊聊怎么在日常写代码时把CPU Cache的性能榨干。

数组遍历方式

我们先来看一个很经典的例子(例子是C语言写的,其他语言实现也都是差不多的):

#include stdio.h #include stdlib.h #include time.h int main() { clock_t begin, end; double cost; begin = clock(); int count = 10000; int* array = (int*)malloc(sizeof(int) * count * count);//2维数组 //代码1 按行遍历 //for (int i = 0;i count;i++) { // for (int j = 0; j count; j++) { // array[i * count + j] = 0; // } //} //代码2 按列遍历 for (int i = 0;i count;i++) { for (int j = 0; j count; j++) { array[j * count + i] = 0; } } end = clock(); cost = (double)(end - begin) / CLOCKS_PER_SEC; printf("constant CLOCKS_PER_SEC is: %ld, time cost is: %lf", CLOCKS_PER_SEC, cost); return 0; }

运行结果:

#代码1 constant CLOCKS_PER_SEC is: 1000, time cost is: 0.126000 #代码2 constant CLOCKS_PER_SEC is: 1000, time cost is: 0.301000

CLOCKS_PER_SEC=1000,表示当前电脑1秒是被分成了1000个时间片,也就是说时间测量最小单位为1ms

所以上述代码1,在笔者的电脑运行耗时大约0.126ms;而代码2,运行耗时却高达0.301ms

两段代码的运算逻辑与总赋值次数完全相同,为什么按列遍历慢了一倍以上?

这2段代码块基本一致,唯独遍历方式不同代码1是按行遍历,而代码2是按列遍历。

本文标签:

更多文章

相关文章

网站导航 | 快讯 | 资讯 | 手机 | 优化 | 系统 | 数码 | 网络通信 | 人工智能

  • 游戏

    合作伙伴:

  • 友情链接(欢迎业界知名网站交换链接)申请友情

    

    声明:本站资源皆来自网络,如有侵权问题,请联系管理员处理!

    Copyright ©2020-2028快知站 版权所有 All rights reserved.

    闽ICP备20010713号-1 闽公网安备 35020602001684号