演算法最佳化--strcpy

來源:互聯網
上載者:User

在很多時候,我們都會使用的strcpy這個函數,我們跟蹤c語言庫的話,會發現它是用彙編寫的。按道理來說效率應該很高,但是我寫了幾個strcpy的函數測試了一下:

char *strcpy1(char *dest, const char *src)
{
 int i = 0;

 while (src[i])
  dest[i++] = src[i];

 dest[i] = '/0';
 return dest;
}

這個是一般的做法,我想大家都能想到。

 

char *strcpy2(char *dest, const char *src)
{
 char *p = dest;

 while (*src)
  *dest++ = *src++;

 *dest = '/0';
 return p;
}

strcpy2的優點是少了一個變數i,可以少一個運算。

 

char *strcpy3(char *dest, const char *src) {
 const char *end = src;
 while (*end)
  end++;
 memcpy(dest, src, end-src+1);
 return dest;
}

這個是我自己寫的,也是要推薦了,要知道mencpy的效率要比按位元組拷貝快的多的多。

下面我們用代碼來測試一下效率:

#include <malloc.h>
#include <STRING.h>
#include <windows.H>
#include <STDIO.H>

void main()
{
 long nSize = 200;
 char* pSource = (char *)malloc(nSize+1);
 char* pDest = (char *)malloc(nSize+1);
 memset(pSource, 'a', nSize);
 pSource[nSize] = '/0';

 DWORD dwStart = GetTickCount();
 for(int i=0; i<5000000; i++)
 {
  strcpy(pDest, pSource);
 }
 DWORD dwEnd = GetTickCount();

 printf("%d", dwEnd-dwStart);
}

我們分兩塊測試,第一塊是小段字串拷貝,如上面的200個位元組。然後我們測試一下10M位元組的,當然迴圈次數只用100次就夠了。

release下測試結果如下:

函數              20位元組                      200位元組                    10M

strcpy              3734                      1734                           2265

strcpy1           2015                       1391                           4219

strcpy2           1953                       1453                           3937

strcpy3           2422                       984                               1890

所以說c標準庫的不一定是最快的。

最後請大家在debug下跑一下看看,你會有新的驚喜,反正我還沒有搞清楚是為什麼。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.