Comparision Among The Access Speed Of Cache , Memory And Disk

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:

1 // Compare.cpp : 定义控制台应用程序的入口点。
2  //
3  
4 #include "stdafx.h"
5 #include <ctime>
6 #include <iostream>
7 #include <fstream>
8
9  using namespace std;
10
11  #define CACHE_TIMES 9000
12  #define CACHE_BLOCK_SIZE 64
13  #define MEMORY_TIMES 1000
14  #define DISK_TIMES 100
15 #define MEMORY_BLOCK_SIZE 4096
16
17 clock_t start, stop; /* clock_t is a built-in type for processor time (ticks) */
18 double duration; /* records the run time (seconds) of a function */
19
20 void TestCache ()
21 {
22 char test[CACHE_TIMES];
23 start = clock();
24
25 for (int i = 0 ; i < CACHE_TIMES*1000 ; i++)
26 {
27 test[i%CACHE_BLOCK_SIZE]++;
28 }
29
30 stop = clock();
31 duration = ((double)(stop - start)*1000000)/(CLK_TCK*CACHE_TIMES);
32 cout << "The time to access cache is : " << duration <<"ns"<< endl;
33 }
34
35 void TestMemory()
36 {
37 char test[MEMORY_TIMES*CACHE_BLOCK_SIZE];
38 char dat;
39 start = clock();
40 for (int i = 0 ; i < MEMORY_TIMES*1000 ; i++)
41 {
42 dat = test[(i*CACHE_BLOCK_SIZE)%(MEMORY_TIMES*CACHE_BLOCK_SIZE)];
43 }
44 stop = clock();
45 duration = ((double)(stop - start)*1000)/(CLK_TCK*MEMORY_TIMES);
46 cout << "The time to access memory is : " << duration <<"us"<< endl;
47 }
48
49 void TestDisk()
50 {
51 ofstream test("test.dat");
52 char dat;
53 char buf[20];
54 for(int i = 0 ; i < DISK_TIMES*MEMORY_BLOCK_SIZE ; i ++)
55 {
56 dat = i % 256;
57 test << dat;
58 }
59 test.close();
60
61 FILE *fp;
62
63 start = clock();
64 fp=fopen("test.dat","r");
65 for (long i = 0 ; i < DISK_TIMES ; i++)
66 {
67 fseek(fp,i*MEMORY_BLOCK_SIZE,SEEK_SET);
68 fread (buf , 1 , 1, fp);
69 }
70 fclose(fp);
71 stop = clock();
72 duration = ((double)(stop - start)*1000)/(CLK_TCK*DISK_TIMES);
73 cout << "The time to access disk is : " <<duration <<"ms"<< endl;
74
75 }
76
77 int _tmain(int argc, _TCHAR* argv[])
78 {
79 TestCache();
80 TestMemory();
81 TestDisk();
82 getchar();
83 return 0;
84 }
85
86

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

原文地址:https://www.cnblogs.com/kking/p/1829607.html