达夫设备(Duff‘s Device)
一、簡介
看到標題,大家也許知道我們要講的內容是什么了。但是很多人可能又對這個達夫設備(Duff's Device)感到很陌生,這到底是什么東東啊?所謂的Duff's Device其實只是一種代碼的特殊寫法,他將switch和do...while結合起來使得算法效率變高,先上代碼:
void fDuffDevice( int * to, int * from, int count) {int n = (count + 7 ) / 8 ;switch (count % 8 ) {case 0 : do { * to ++ = * from ++ ;case 7 : * to ++ = * from ++ ;case 6 : * to ++ = * from ++ ;case 5 : * to ++ = * from ++ ;case 4 : * to ++ = * from ++ ;case 3 : * to ++ = * from ++ ;case 2 : * to ++ = * from ++ ;case 1 : * to ++ = * from ++ ;} while ( -- n > 0 );} }可能初看,會覺得這個代碼很奇怪,能否編譯通過呢?親自測試了一下,能夠正常編譯。
二、代碼分析
我們寫了一段測試代碼,具體如下:
#include <stdio.h>void fDuffDevice( int * to, int * from, int count) {int n = (count + 7 ) / 8 ;switch (count % 8 ) {case 0 : do { * to ++ = * from ++ ;printf("case 0 :Running\n");case 7 : * to ++ = * from ++ ;printf("case 7 :Running\n");case 6 : * to ++ = * from ++ ;printf("case 6 :Running\n");case 5 : * to ++ = * from ++ ;printf("case 5 :Running\n");case 4 : * to ++ = * from ++ ;printf("case 4 :Running\n");case 3 : * to ++ = * from ++ ;printf("case 3 :Running\n");case 2 : * to ++ = * from ++ ;printf("case 2 :Running\n");case 1 : * to ++ = * from ++ ;printf("case 1 :Running\n");} while ( -- n > 0 );} } int main() {int i = 0; int to[20] = {0};int from[20] = {0};for(i = 0 ;i < 20 ;i++)from[i] = i; fDuffDevice(to,from,20);for(i = 0 ;i < 20 ;i++)printf("to[%d] = %d;\n", i ,to[i]);return 0; }以下是打印出來的效果:(具體的運行順序不用我再講了吧!)?
case 4 :Running case 3 :Running case 2 :Running case 1 :Running case 0 :Running case 7 :Running case 6 :Running case 5 :Running case 4 :Running case 3 :Running case 2 :Running case 1 :Running case 0 :Running case 7 :Running case 6 :Running case 5 :Running case 4 :Running case 3 :Running case 2 :Running case 1 :Running to[0] = 0; to[1] = 1; to[2] = 2; to[3] = 3; to[4] = 4; to[5] = 5; to[6] = 6; to[7] = 7; to[8] = 8; to[9] = 9; to[10] = 10; to[11] = 11; to[12] = 12; to[13] = 13; to[14] = 14; to[15] = 15; to[16] = 16; to[17] = 17; to[18] = 18; to[19] = 19;?
三、意義
我們一般使用用for循環或者while循環的時候,如果執行循環內容本身用不了多少時間,本質上時間主要是消耗在了每次循環的比較語句上邊。而事實上,比較語句是有很大優化空間的,我們假設你要循環10000次,結果你從第一次開始就不斷的比較是否達到上界值,這是不是很徒勞呢?而達夫設備(Duff's Device)可以大大減少這種比較,我們可以看到,上面的代碼,8次才進行一次比較。這樣就大大節約了時間。提高了效率。
四、寫在最后的話
這種寫法不是很值得我們借鑒。畢竟這不是符合我們“正常”邏輯的代碼,至少C/C++標準不會保證這樣的代碼一定不會出錯。另外, 這種代碼冷知識,估計有很多人根本都沒見過,如果自己寫的代碼別人看不懂,估計會被罵的。雖然我覺得達夫設備是個很高效、很值得我們去學習的東西。把一次消耗相對比較高的操作“分攤“到了多次消耗相對比較低的操作上面,就像vector中實現可變長度的數組的思想那樣,節省了大量的機器資源,也大大提高了程序的效率。
總結
以上是生活随笔為你收集整理的达夫设备(Duff‘s Device)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 二、制作最小linux系统
- 下一篇: 最轻量级的C协程库:Protothrea