程序在运行的过程访问主存每次是按cpu cache line 64B访问的(主流cpu cache line一般都是64B),如果命中L1 cache耗时约1ns,如果命中L2 cache耗时约3ns,如果命中L3 cache耗时约12ns,如果访问内存约50-100ns,上面这些数据都是从些网上的文章资料得知的。
如何写段代码测试下内存的访问时间,结果应该接近50-100ns ,本文介绍下测试方法:
1. 申请几段连续的虚拟内存,总大小4GB;
2. 给申请的4GB内存按页的大小4KB间隔,每页第1个字节写入值,目的是访问内存,让系统真正的分配物理内存;
3. 按照步长64B 128B … 4096B分别测试下按顺序访问已申请的4GB内存;
注:测试机器要尽量干净,未运行服务程序,以免测试过程中产生cpu切出运行其它服务程序,影响计时;
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
long long ustime(void)
{
struct timeval tv;
long long ust;
gettimeofday(&tv, NULL);
ust = ((long)tv.tv_sec)*1000000;
ust += tv.tv_usec;
return ust;
}
#define LOOPLEN 4*1024
#define STEPLEN 64
#define LOOPLENREFRSH 512
typedef struct bigData{
char buf[1024*1024]; /* 1MB buffer */
} bigData;
struct bigData * apstData[LOOPLEN];
struct bigData * apstDataTmp[LOOPLENREFRSH];
void test()
{
long long t1;