gpt4 book ai didi

c - 高效复制内存

转载 作者:太空狗 更新时间:2023-10-29 15:41:55 25 4
gpt4 key购买 nike

我继承了以下代码:

void *buf1 = calloc(1,total_buf_size);
//build buf1 up with memcpy
int index;
void *buf2 = buf1;

for (index = 0; index < log->numentries; index++)
{
logentry_t *entry = (logentry_t*)&log->entries[index];

memcpy(buf2,entry->entryname,sizeof(entry->entryname));
buf2 = buf2 + (int)sizeof(entry->entryname);
memcpy(buf2,&entry->entrysize,sizeof(entry->entrysize));
buf2 = buf2 + (int)sizeof(entry->entrysize);
memcpy(buf2,&entry->updatesize,sizeof(entry->updatesize));
buf2 = buf2 + (int)sizeof(entry->updatesize);
memcpy(buf2,&entry->numupdates,sizeof(entry->numupdates));
buf2 = buf2 + (int)sizeof(entry->numupdates);

int j;
for (j = 0; j < entry->numupdates; j++)
{
memcpy(buf2,&entry->offsets[j],sizeof(entry->offsets[j]));
buf2 = buf2 + (int)sizeof(entry->offsets[j]);
}

int k;
for (k = 0; k < entry->numupdates; k++)
{
memcpy(buf2,&entry->sizes[k],sizeof(entry->sizes[k]));
buf2 = buf2 + (int)sizeof(entry->sizes[k]);
}


memcpy(buf2,entry->data,entry->updatesize);
}

我有一个正在迭代的事务日志,需要将每个日志条目的数据写入文件中的一行。目前,它正在使用 memcpy 构建所有条目的缓冲区,并将它们一次性全部写入文件。有没有更好的方法将内存复制扩展到buf2?

最佳答案

我不确定您到底在寻找什么样的效率,但这里有一个将每个日志条目记录写入文件然后为每次迭代重置缓冲区 buf2 的示例。因此,您可以将 buf1 大小(由 total_buf_size 定义)减小到只适合一个日志条目记录的大小:

void *buf1 = calloc(1,total_buf_size);
//With this method total_buf_size can be reduced to fit just one log entry record

//build buf1 up with memcpy
int index;
void *buf2 = buf1;

FILE * pFile;
pFile = fopen ("myfile.txt","w");

for (index = 0; index < log->numentries; index++)
{
logentry_t *entry = (logentry_t*)&log->entries[index];

memcpy(buf2,entry->entryname,sizeof(entry->entryname));
buf2 = buf2 + (int)sizeof(entry->entryname);
memcpy(buf2,&entry->entrysize,sizeof(entry->entrysize));
buf2 = buf2 + (int)sizeof(entry->entrysize);
memcpy(buf2,&entry->updatesize,sizeof(entry->updatesize));
buf2 = buf2 + (int)sizeof(entry->updatesize);
memcpy(buf2,&entry->numupdates,sizeof(entry->numupdates));
buf2 = buf2 + (int)sizeof(entry->numupdates);

int j;
for (j = 0; j < entry->numupdates; j++)
{
memcpy(buf2,&entry->offsets[j],sizeof(entry->offsets[j]));
buf2 = buf2 + (int)sizeof(entry->offsets[j]);
}

int k;
for (k = 0; k < entry->numupdates; k++)
{
memcpy(buf2,&entry->sizes[k],sizeof(entry->sizes[k]));
buf2 = buf2 + (int)sizeof(entry->sizes[k]);
}


memcpy(buf2,entry->data,entry->updatesize);

fwrite(buf2, sizeof(logentry_t), sizeof(buf2), pFile);

memset(&buf2, 0, sizeof(buf2)); //clear it out
buf2 = buf1; //reset the pointer
}

fclose(pFile);
free(buf2);

关于c - 高效复制内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29681108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com