記憶體對齊效能測試

來源:互聯網
上載者:User

記憶體對齊的重要性大家都知道, 那麼記憶體不對齊, 對效能有多大的影響?  本文做個小實驗:

#include <stdio.h>#include <stdlib.h>#include "ctimer.h"int main(){    char buf[512];    printf("buf[0]'s addr [%x][%d]\n", (int)(char*)&buf[0],(int)(char*)&buf[0]);    printf("buf[1]'s addr [%x][%d]\n", (int)(char*)&buf[1],(int)(char*)&buf[1]);    CMyTimer t1;    int tmp = 0;    int count = 1000000;    memset(buf, sizeof(buf), 0);    t1.Begin();    for (int i=0; i<count; ++i)    {        for (int j=1;j<(sizeof(buf)-4);j+=4)        {            tmp = *(int*)&buf[j];            tmp++;            *(int*)&buf[j] = tmp;        }    }    printf("use time : %5.1f\n", t1.GetElapseTimeMS());    memset(buf, sizeof(buf), 0);    t1.Begin();    for (int i=0; i<count; ++i)    {        for (int j=2;j<(sizeof(buf)-4);j+=4)        {            tmp = *(int*)&buf[j];            tmp++;            *(int*)&buf[j] = tmp;        }    }    printf("use time : %5.1f\n", t1.GetElapseTimeMS());    memset(buf, sizeof(buf), 0);    t1.Begin();    for (int i=0; i<count; ++i)    {        for (int j=3;j<(sizeof(buf)-4);j+=4)        {            tmp = *(int*)&buf[j];            tmp++;            *(int*)&buf[j] = tmp;        }    }    printf("use time : %5.1f\n", t1.GetElapseTimeMS());    memset(buf, sizeof(buf), 0);    t1.Begin();    for (int i=0; i<count; ++i)    {        for (int j=0;j<(sizeof(buf)-4);j+=4)        {            tmp = *(int*)&buf[j];            tmp++;            *(int*)&buf[j] = tmp;        }    }    printf("use time : %5.1f\n", t1.GetElapseTimeMS());    return 0;}

測試結果如下:

buf[0]'s addr [bfa26aac][-1079874900]buf[1]'s addr [bfa26aad][-1079874899]use time : 936.6use time : 979.9use time : 980.4use time : 769.9 // 可以看到對齊後的效果要好點

基本上  (980-770)/980 = 0.21. 有21%的效能差異.

程式邏輯解釋:
1) 首先在棧上申請buf, 一般情況下, buf的首地址都是記憶體對齊後的 (編譯器不會那麼傻, 給使用者在棧上分配一個地址不對齊的變數)
2) 然後做了4各個測試. 第一個測試, 錯位一個位元組, 每次讀取一個整形,再寫入一個整形. 後面依次錯位2,3,0位元組. 其中最後一次相當於沒有錯位.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.