我打算開個長篇系列部落格,預計108篇吧,但願能在1-2年內完成。
註:考慮到我本人長期使用linux系統做開發,因此有些代碼在windows環境下無法編譯或者會有問題,建議大家都使用linux環境做實驗,最好是2.6核心的,處理器需要是多核。很多讀者說我是紙上談兵,這個確實不好,從本系列開始基本都是50行左右的代碼。本系列不代表任何學術或業界立場,僅我個人興趣愛好,由於水平有限,錯誤難免,請不要有過分期望。
廢話不多說,今天就寫第一篇如下:
以下一段代碼分別編譯成兩個程式,僅僅是變數定義的差別,執行時間差距巨大,這是什麼原因呢?
本部落格暫不解密,等數天后,我把後半部寫上,希望讀者朋友們踴躍實驗,並回答。
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#ifdef FS
size_t cnt_1;
size_t cnt_2;
#endif
#ifdef NONFS
size_t __attribute__((aligned(64))) cnt_1;
size_t __attribute__((aligned(64))) cnt_2;
#endif
void* sum1(void*)
{
for(int i=0;i < 10000000;++i) {
cnt_1 += 1;
}
};
void* sum2(void*)
{
for(int i=0;i < 10000000;++i) {
cnt_2 += 1;
}
};
int main()
{
pthread_t* thread = (pthread_t*) malloc(2*sizeof( pthread_t));
pthread_create(&thread[0],NULL,sum1,NULL); //建立2個線程分別求和
pthread_create(&thread[1],NULL,sum2,NULL);
pthread_join(thread[0],NULL); //等待2個線程結束計算。
pthread_join(thread[1],NULL);
free(thread);
printf("cnt_1:%d,cnt_2:%d",cnt_1,cnt_2);
}
編譯方法:
g++ fs.cpp -o test_nfs -g -D NONFS –lpthread
g++ fs.cpp -o test_fs -g -D FS –lpthread
用time ./test_nfs 和 time ./test_fs會發現執行時間差別很大,請讀者踴躍跟帖作答,謝謝。
續篇參見:http://blog.csdn.net/pennyliang/archive/2010/10/26/5966433.aspx
網友linyai做了實驗,大家可以參考一下,以下來自跟帖。
linyai 發表於Thu Oct 21 2010 10:11:22 GMT+0800 (China Standard Time) 舉報回複刪除
fs: 0m0.083s nfs: 0m0.043s fs: 0m0.130s nfs: 0m0.034s fs: 0m0.084s nfs: 0m0.037s fs: 0m0.086s nfs: 0m0.042s