[英]Implementing a strcpy function in C
我的任務是這樣的:我需要在以下約束下實現strcpy
函數:
strcpy
的函數中,目標地址將保持如下: char* newDestination = NULL;
strcpy
函數的原型應為: void myStrcp(void** dst, void* src);
我提出了使用uint64_t
復制每個迭代八個字節的解決方案。 如果是這樣,我的問題是:
Windows
vs Linux
)和/或平台上運行程序是否重要? #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <conio.h>
void strCpy(void **dst, void *src);
int main()
{
char *newLocation = NULL;
strCpy((void **)&newLocation, "stringToBeCopied");
printf("after my strcpy dst has the string: %s \n", newLocation);
free(newLocation);
getch();
return 0;
}
void strCpy(void** dst, void* src)
{
// Allocating memory for the dst string
uint64_t i, length = strlen((char *)src), *locDst =
(uint64_t *) malloc(length + 1), *locSrc = (uint64_t *) src;
*dst = locDst;
// Copy 8 Bytes each iteration
for (i = 0; i < length / 8; *locDst++ = *locSrc++, ++i);
// In case the length of the string is not alligned to 8 Bytes - copy the remainder
// (last iteration)
char *char_dst = (char *)locDst, *char_src = (char *)locSrc;
for (; *char_src != '\0'; *char_dst++ = *char_src++);
// NULL terminator
*char_dst = '\0';
}
向量化確實是關鍵。 同樣的想法,更好的解決方案是使用SSE / AVX以獲得更有效的副本。 當然,這可以根據需要確定特定於程序平台的位置,以檢測所支持的最大矢量化。
您還應該解決幾個問題:
src / dst的對齊方式-如果您復制的塊(在上面的示例中為64位)超過了緩存行,則由於緩存行拆分,硬件很可能會在執行復制時產生開銷。 在較長的向量中,開銷可能會變得更大(並且在那里的頻率也更高)。 因此,您可以添加一些初始檢查來解決此問題,方法是像處理尾巴一樣,將頭分成較小的塊來復制。
src / dst區域會發生沖突嗎? 如果是這樣,則需要為正確的功能行為提供定義(在分塊復制的情況下,它變得不那么瑣碎了)。
注意strcpy和memcpy之間的區別(另請參見此處 )。 這使得矢量化變得不那么瑣碎,因此您需要在此處定義要求。 當前,您的功能可能與傳統strcpy中的功能有所不同,因為您不檢查每個塊中的空字節。 不確定這是否對您有問題。
代碼大小限制不是非常友好的性能(嗯,除非瓶頸是指令緩存容量或分支可預測性,但這是相當先進的)。 這7句話的限制可能意味着您對這個想法太過思索了:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.