速度测试代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/time.h> #include <sched.h> #define COUNT 10000000 //#define COUNT 10000000 #define MILLION 1000000L size_t VisCore_Strlcpy(char *dst, const char *src, size_t n) { const char *src0 = src; char dummy[1]; if (!n) { dst = dummy; } else { --n; } while ((*dst = *src) != 0) { if (n) { --n; ++dst; } ++src; } return src - src0; } int main(void) { int i; long long tdif; struct timeval tend, tstart; char data[1024]; char *buf1 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaababbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"; char *buf = "aaaaaaaaaaaaaaaaaaaaaaaa"; if (gettimeofday(&tstart, NULL) == -1) { fprintf(stderr, "Failed to get start time "); return 1; } #if 1 for (i = 0; i < COUNT; i++) { //snprintf(data, sizeof(data), "%s", buf); //snprintf(data, sizeof(data), "%s", buf); //strlcpy(data, buf, sizeof(data)); VisCore_Strlcpy(data, buf, sizeof(data)); //strncpy(data, buf, sizeof(data)); } #endif if (gettimeofday(&tend, NULL) == -1) { fprintf(stderr, "Failed to get end time "); return 1; } tdif = MILLION * (tend.tv_sec - tstart.tv_sec) + (tend.tv_usec - tstart.tv_usec); //printf("nanosleep() time is %lld us ", tdif); printf("nanosleep() time is %f us ", tdif*1.0/COUNT); //printf("nanosleep() time is %lld us ", tdif/COUNT); return 0; }
在hi3520a中的测试速度结果:
源、目标长度大小 相关函数 |
dst:24 src:678 | dst:680 src:678 | dst:1024 src:678 | dst:1024 src:24 |
strncpy(us) O2 优化 | 0.037871 | 2.408301 | 3.155248 | 2.264491 |
snprintf(us) O2 优化 | 3.061944 | 3.320676 | 3.311918 | 1.46123 |
strlcpy(us) O2 优化 | 3.681469 | 3.681542 | 3.681374 | 0.174848 |
VisCore_Strlcpy(us) O2 优化 | 2.934305 | 2.571704 | 2.57172 | 0.108673 |
源、目标长度大小 相关函数 |
dst:24 src:678 | dst:680 src:678 | dst:1024 src:678 | dst:1024 src:24 |
strncpy(us) O2 优化 | 0.037871 | 2.408301 | 3.155248 | 2.264491 |
snprintf(us) O2 优化 | 3.061944 | 3.320676 | 3.311918 | 1.46123 |
strlcpy(us) O2 优化 | 3.681469 | 3.681542 | 3.681374 | 0.174848 |
VisCore_Strlcpy(us) O2 优化 | 2.934305 | 2.571704 | 2.57172 | 0.108673 |
strlcpy(us) Os 优化 | 3.684127 | 3.684136 | 3.68421 | 0.165779 |
VisCore_Strlcpy(us) Os 优化 | 3.678672 | 3.678688 | 3.678671 | 0.185096 |
VisCore_Strlcpy(us) O0 默认 | 16.902501 | 18.300108 | 18.302474 | 0.710118 |
参考博文:
[原创]snprintf与strncpy效率对比
aa