C語言程式設計常用數值計算的高效能實現

2021-07-11 09:39:36 字數 2048 閱讀 5471

本篇介紹一組非常簡單卻又很常用的數值計算的巨集實現。本篇所提到的數值計算問題,相信c語言初學者都能做得出來,但是本篇中給出的例子實現卻更注重效率。這些例子實現的最大特點是,消除了邏輯跳轉。這樣做的好處是避免了分支**的風險,或者換句話說,可以更好地發揮處理器流水線的效能。由於本篇的問題都很簡單,筆者就廢話少說,直接看例子了。

/* 高位全0,低n位全1 */

#define low_n_bits_one(n) ((1<>3)

#define div16(num) ((num)>>4)

#define div32(num) ((num)>>5)

/* 餘數進製求商 */

#define updiv8(num) (((num)>>3) + !!((num) & 0x7))

#define updiv16(num) (((num)>>4) + !!((num) & 0xf))

#define updiv32(num) (((num)>>5) + !!((num) & 0x1f))

/* 求餘 */

#define m8(num) ((num) & 0x7)

#define m16(num) ((num) & 0xf)

#define m32(num) ((num) & 0x1f)

/* 求反餘

即求最小的x,滿足(num + x) % 模數 == 0

例如 rm16(num) 等價於 (16 - num%16) % 16 */

#define rm8(num) ((~(num) + 1) & 0x7)

#define rm16(num) ((~(num) + 1) & 0xf)

#define rm32(num) ((~(num) + 1) & 0x1f)

最後,再列出gcc提供的位操作相關的部分built-in函式

int __builtin_ffs (unsigned int x)

returns one plus the index of the least significant 1-bit of x, or if x is zero, returns zero.

int __builtin_clz (unsigned int x)

returns the number of leading 0-bits in x, starting at the most significant bit position.

if x is 0, the result is undefined.

int __builtin_ctz (unsigned int x)

returns the number of trailing 0-bits in x, starting at the least significant bit position.

if x is 0, the result is undefined.

int __builtin_clrsb (int x)

returns the number of leading redundant sign bits in x, i.e. the number of bits

following the most significant bit that are identical to it. there are no special cases

for 0 or other values.

int __builtin_popcount (unsigned int x)

returns the number of 1-bits in x.

int __builtin_parity (unsigned int x)

returns the parity of x, i.e. the number of 1-bits in x modulo 2.

上述函式的運算元寬度是int。

如果在上述函式名後面加上l或ll,則運算元寬度就分別對應long或long long。

Go 語言高效能程式設計

第一章 效能分析 第二章 常用資料結構 第三章 併發程式設計 第四章 編譯優化 附錄 go 語言陷阱 go 語言筆試面試題 我使用 go 作為主力程式語言已經有一年多的時間了,主要的工作職責是開發一些效率工具,例如分布式編譯加速工具。對效能不太敏感的地方,通常會使用 python,因為 python...

鍊錶數值計算(C語言)

需要考慮到如下問題 1 由鍊錶儲存的數怎麼轉化為可以進行運算的數值 2 數值的儲存採用哪種資料型別,考慮運算過程中數值可能會超過定義的資料型別值的範圍,採用陣列形式儲存解決溢位問題 3 陣列形式的數值怎麼進行加法運算 4 數值結果如何轉化為可用鍊錶儲存的形式 include include defi...

C語言數值表示和計算

恢復內容開始 一 資料型別 在我的windows上檢視可以看到對資料型別長度的定義 define shrt min 32768 minimum signed short value define shrt max 32767 maximum signed short value define ush...