【发布时间】:2016-08-18 05:56:19
【问题描述】:
下面是我的一段程序,它使用哈希表将文件(字典)加载到内存中。该词典每行仅包含 1 个单词。但是这个过程花费了太多时间。如何优化它??
bool load(const char* dictionary)
{
// TODO
int k;
FILE* fp = fopen(dictionary,"r");
if(fp == NULL)
return false;
for(int i=0; i<26; i++)
{
hashtable[i] = NULL;
}
while(true)
{
if(feof(fp))
return true;
node* n = malloc(sizeof(node));
n->pointer = NULL;
fscanf(fp,"%s",n->word);
if(isalpha(n->word[0]))
{
k = hashfunction(n->word);
}
else return true;
if(hashtable[k] == NULL)
{
hashtable[k] = n;
total_words++;
}
else
{
node* traverse = hashtable[k];
while(true)
{
if(traverse->pointer == NULL)
{
traverse->pointer = n;
total_words++;
break;
}
traverse = traverse->pointer;
}
}
}
return false;
}
【问题讨论】:
-
文件中有多少字(行)?
hashfunction是做什么的?您是否尝试过增加存储桶的数量以便不需要那么多列表遍历?但最重要的是,您是否尝试过使用 profiler 来找出瓶颈所在? -
与您的问题无关,但您的阅读循环与
while (!feof(fp))、which is wrong 没有太大区别。 -
这是“工作”代码。如果您想了解如何使其“更好”,请在codereview.stackexchange.com 上发布此内容。这样做时,你应该包括你的哈希函数和驱动程序代码,以及你正式测试它的任何方式的注释和测量。
-
@WhozCraig 这不是完整的代码,所以这里或那里都无法回答。