您的位置:首页 > 其它

Comparision Among The Access Speed Of Cache , Memory And Disk

2010-09-17 21:40 549 查看
The first homework of db design is to compare the speed of accessing cache , meory and disk. This experiment show the gap among them.

To test the accecc time of cache , I use cpu-z to find that the block size in my cpu cache is 64 byte. That means I can create a 64-byte-size array and access it repeatly to estimate the accecc time.

The block size in my main memory with win7 is 4k. So i make a array and access it every 4k byte sequentially.

To obtain the time of accessing disk, a large file will be readed every at intervals of 4k byte.

here i show the c++ code:

// Compare.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <ctime>
#include <iostream>
#include <fstream>

using namespace std;

#define CACHE_TIMES 9000
#define CACHE_BLOCK_SIZE 64
#define MEMORY_TIMES 1000
#define DISK_TIMES 100
#define MEMORY_BLOCK_SIZE 4096

clock_t  start, stop; /* clock_t is a built-in type for processor time (ticks) */
double  duration;  /* records the run time (seconds) of a function */

void  TestCache ()
{
char test[CACHE_TIMES];
start = clock();

for (int i = 0 ; i < CACHE_TIMES*1000 ; i++)
{
test[i%CACHE_BLOCK_SIZE]++;
}

stop = clock();
duration = ((double)(stop - start)*1000000)/(CLK_TCK*CACHE_TIMES);
cout << "The time to access cache is  : " << duration <<"ns"<< endl;
}

void TestMemory()
{
char test[MEMORY_TIMES*CACHE_BLOCK_SIZE];
char dat;
start = clock();
for (int i = 0 ; i < MEMORY_TIMES*1000 ; i++)
{
dat = test[(i*CACHE_BLOCK_SIZE)%(MEMORY_TIMES*CACHE_BLOCK_SIZE)];
}
stop = clock();
duration = ((double)(stop - start)*1000)/(CLK_TCK*MEMORY_TIMES);
cout << "The time to access memory is  : " << duration <<"us"<< endl;
}

void TestDisk()
{
ofstream test("test.dat");
char dat;
char buf[20];
for(int i = 0 ; i < DISK_TIMES*MEMORY_BLOCK_SIZE ; i ++)
{
dat = i % 256;
test << dat;
}
test.close();

FILE *fp;

start = clock();
fp=fopen("test.dat","r");
for (long i = 0 ; i < DISK_TIMES ; i++)
{
fseek(fp,i*MEMORY_BLOCK_SIZE,SEEK_SET);
fread (buf , 1 , 1, fp);
}
fclose(fp);
stop = clock();
duration = ((double)(stop - start)*1000)/(CLK_TCK*DISK_TIMES);
cout << "The time to access disk is  : " <<duration <<"ms"<< endl;

}

int _tmain(int argc, _TCHAR* argv[])
{
TestCache();
TestMemory();
TestDisk();
getchar();
return 0;
}


result:

The time to access cache is : 4.88889ns
The time to access memory is : 0.014us
The time to access disk is : 0.01ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐