【发布时间】:2010-12-14 19:40:49
【问题描述】:
我编写了一个函数,用于将 64 位整数转换为基数 62 字符串。最初,我是这样实现的:
char* charset = " 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int charsetLength = strlen(charset);
std::string integerToKey(unsigned long long input)
{
unsigned long long num = input;
string key = "";
while(num)
{
key += charset[num % charsetLength];
num /= charsetLength;
}
return key;
}
但是,这太慢了。
我通过提供生成查找表的选项提高了速度。该表的大小约为 624 个字符串,生成如下:
// Create the integer to key conversion lookup table
int lookupChars;
if(lookupDisabled)
lookupChars = 1;
else
largeLookup ? lookupChars = 4 : lookupChars = 2;
lookupSize = pow(charsetLength, lookupChars);
integerToKeyLookup = new char*[lookupSize];
for(unsigned long i = 0; i < lookupSize; i++)
{
unsigned long num = i;
int j = 0;
integerToKeyLookup[i] = new char[lookupChars];
while(num)
{
integerToKeyLookup[i][j] = charset[num % charsetLength];
num /= charsetLength;
j++;
}
// Null terminate the string
integerToKeyLookup[i][j] = '\0';
}
实际的转换如下所示:
std::string integerToKey(unsigned long long input)
{
unsigned long long num = input;
string key = "";
while(num)
{
key += integerToKeyLookup[num % lookupSize];
num /= lookupSize;
}
return key;
}
这大大提高了速度,但我仍然相信它可以改进。 32 位系统上的内存使用量约为 300 MB,而 64 位系统上则超过 400 MB。看起来我应该能够减少内存和/或提高速度,但我不确定如何。
如果有人能帮我弄清楚如何进一步优化此表,我将不胜感激。
【问题讨论】:
-
在你的第一个版本中,我认为
key /= charsetLength;应该是num /= charsetLength;。 -
与您的主要问题无关,但您可能希望将字符集声明为
const。 -
@sbi:但是尝试优化无限循环非常有趣。
-
糟糕,很抱歉。我从内存中重写了这段代码,只是为了说明我在应用程序中是如何做事的。我会解决的。
-
base64 会快很多,而且已经有很多为此优化的库
标签: c++ optimization lookup modulo