[英]Just out of curiosity: how come linux kernel “optimized” strcpy is much slower the libc imp?
我嘗試在http://lxr.linux.no/#linux+v2.6.38/arch/x86/lib/string_32.c下對優化的字符串操作進行基准測試,並與常規strcpy進行比較:
#include<stdio.h>
#include<stdlib.h>
char *_strcpy(char *dest, const char *src)
{
int d0, d1, d2;
asm volatile("1:\tlodsb\n\t"
"stosb\n\t"
"testb %%al,%%al\n\t"
"jne 1b"
: "=&S" (d0), "=&D" (d1), "=&a" (d2)
: "0" (src), "1" (dest) : "memory");
return dest;
}
int main(int argc, char **argv){
int times = 1;
if(argc >1)
{
times = atoi(argv[1]);
}
char a[100];
for(; times; times--)
_strcpy(a, "Hello _strcpy!");
return 0;
}
並使用(time ..)對其計時,表明它比常規strcpy慢x10(在x64 linux下)
為什么?
如果您的字符串是常量,則編譯器可能會內聯該副本(用於普通的strcpy
調用),從而使其成為一系列無條件的MOV指令。 由於這是沒有條件的線性代碼,因此它將比linux變體更快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.