看板 C_and_CPP 關於我們 聯絡資訊
先貼上代碼 使用編譯器是Visual C++ 電腦32位元 #include <stdio.h> #include <memory.h> #include <stdlib.h> #include <time.h> #define len 1000 #define times 10000 #define type long long type c[len][len]; int main() { int timer[2]; timer[0] = clock(); int i = times, j = times; while (i--) { memset(c, 1, sizeof(type)*len*len); } timer[1] = clock(); printf("%f\n", double(timer[1] - timer[0]) / CLOCKS_PER_SEC); timer[0] = clock(); while (j--) { for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { c[i][j] = 0; } } } timer[1] = clock(); printf("%f\n", double(timer[1] - timer[0]) / CLOCKS_PER_SEC); system("pause"); } 還想請問大大們一些問題 1.當我define type為bool char int 速度都差不多反而是迴圈有快一些些 當我設定為long long的時候 迴圈的做法時間會暴增這是為什麼? 我本來預想結果是 bool memset 快 char 一樣 int for 快 主要是因為我以為形態越大對於用迴圈的作法是不是更有利 2.當我把c變數設定在全域時才測的出來數值放在main裡面的話怎麼測都是0 是不是全域變數存取會比較久? 3.class和struct是不是不需要另外去清0?我測試的時候所有成員變數預設都是0耶 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 121.254.69.174 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1424035672.A.94E.html
dritchie: long long可以視為兩個int綁在同一個變數上 02/16 08:01
wenyonba: 我怎麼覺得你第二個while應該會永遠跑不完... 02/16 08:02
dritchie: 所以long long=0其實內部是兩次assignment 02/16 08:02
wenyonba: 喔喔,你的 for 裡面又 define 了 j,sorry 02/16 08:03
dritchie: 剩下的讀書吧 "程式設計師的自我修養" 02/16 08:04
wenyonba: 這樣宣告看起來好花啊... 02/16 08:05
ji2my: define請用大寫 02/16 11:48
littleshan: 1. 你有開最佳化嗎?我用 gcc -O3 結果就和你相反了 02/16 14:00
littleshan: 2. 宣告為 local 很可能會 stack overflow 02/16 14:01
littleshan: 3. 使用memset填非0值很可能造成undefined behavior 02/16 14:02
littleshan: 4. long long 不一定是兩個 int 02/16 14:04
lintsu: 要下最佳化參數在實驗 02/16 18:10
MashiroKinji: 那麼如果要清0還是建議用memset嗎? 02/16 20:48
akasan: 用 memset, compiler 知道你在幹麻可以翻出更好的東西 02/17 00:59
akasan: 某些情況下你自己用 for 去清成 0, compiler 也認的出來 02/17 01:00