- 論壇徽章:
- 0
|
網(wǎng)上搜了搜,都說memcpy比strcpy快,理論上來說也能說得通。但運行的結(jié)果讓我大吃一驚。strcpy比memcpy快40%- //g++ -g malloc.c
- #include <stdlib.h>
- #include <stdio.h>
- #include <sys/time.h>
- #include <string.h>
- #define SIZE 128
- struct timeval begin, end;
- char source[SIZE], destination[SIZE];
- void mcp(char* dst, char* src, int len, int num)
- {
- for(int i = 0; i<num; i++)
- {
- memcpy(dst, src, len);
- }
- }
- void strcopy(char* dst, char* src, int num)
- {
- for(int i = 0; i<num; i++)
- {
- strcpy(dst, src);
- }
- }
- int main(int argc, char** argv)
- {
- int num;
- if ( argc < 2 )
- {
- printf("usage: %s num\n", argv[0]);
- exit(1);
- }
- num = atoi(argv[1]);
- memset(source, 0x21, sizeof(source));
- source[sizeof(source)-1] = '\0';
- gettimeofday(&begin, NULL);
- mcp(destination, source, 128, 600000);
- gettimeofday(&end, NULL);
- printf("dur: %u seconds, %u micro sec\n", end.tv_sec-begin.tv_sec, end.tv_usec-begin.tv_usec);
-
- gettimeofday(&begin, NULL);
- strcopy(destination, source, 600000);
- gettimeofday(&end, NULL);
- printf("dur: %u seconds, %u micro sec\n", end.tv_sec-begin.tv_sec, end.tv_usec-begin.tv_usec);
- return 0;
- }
復制代碼 #:~/test$ ./a.out 2
dur: 0 seconds, 64623 micro sec
dur: 0 seconds, 46371 micro sec |
|