最快的基本转换方法? [英] Fastest base conversion method?
问题描述
现在我正在处理一个项目,需要一个整数转换为一个基础的62字符串,每秒多次。这个转换完成得越快越好。
Right now I'm working on a project which requires an integer to be converted to a base 62 string many times a second. The faster this conversion is completed, the better.
问题是,我很难得到自己的基本转换方法快速和可靠。如果我使用字符串,它通常可靠,工作很好,但它很慢。如果我使用字符数组,它通常快得多,但它也是非常混乱,不可靠。 (它会产生堆损坏,应该匹配的字符串的比较返回一个否定的等等)
The problem is that I'm having a hard time getting my own base conversion methods to be fast and reliable. If I use strings, it's generally reliable and works well, but it's slow. If I use char arrays, it's generally much faster, but it's also very messy, and unreliable. (It produces heap corruption, comparison of strings that should match return a negative, etc.)
那么,最快和最可靠的方法是从一个非常大的整数基地62键?在未来,我计划在我的应用程序中使用SIMD模型代码,所以这个操作是否可以并行化?
So what's the fastest and most reliable way of converting from a very large integer to a base 62 key? In the future, I plan on utilizing SIMD model code in my application, so is this operation parallelizable at all?
编辑:此操作每秒执行几百万次;一旦操作完成,它再次作为循环的一部分开始,因此运行得越快,越好。正在转换的整数是任意大小的,可以容易地大到128位整数(或更大)。
This operation is performed several million times a second; as soon as the operation finishes, it begins again as part of a loop, so the faster it runs, the better. The integer being converted is of arbitrary size, and can easily be as large as a 128 bit integer (or larger).
编辑:这是我目前使用的函数
This is the function I am currently using.
char* charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int charsetLength = (int)(strlen(charset));
//maxChars is an integer specifying the maximum length of the key
char* currentKey = new char[maxChars];
void integerToKey(unsigned long long location)
{
unsigned long long num = location;
int i = 0;
for(; num > 0; i++)
{
currentKey[i] = charset[num % (charsetLength)];
num /= charsetLength + 1;
}
currentKey[i + 1] = '\0';
}
我从我的应用程序的一个类中剥离了这个,
I ripped this out of a class that is part of my application, and some of the code is modified so that it makes sense sans its owning class.
推荐答案
可能你想要的是一些版本的itoa。这里是一个链接,显示各种版本的itoa与性能测试:
http:/ /www.jb.man.ac.uk/~slowe/cpp/itoa.html
Probably what you want is some version of itoa. Here is a link that shows various versions of itoa with performance tests: http://www.jb.man.ac.uk/~slowe/cpp/itoa.html
一般来说,我知道有两种方法。一种方式是执行连续分割以一次剥离一个数字。另一种方法是在块中预先计算转换。所以你可以预计算一个块的大小为62 ^ 3的文本转换,然后一次做数字3。如果你有效地执行内存布局和查找,运行时可能会稍微快些,但会导致启动惩罚。
In general, I know of two ways to do this. One way it to perform successive divisions to strip off one digit at a time. Another way is to precompute conversions in "blocks". So you could precompute a block of int to text conversion of size 62^3 then do the digits 3 at a time. Provided you do the memory layout and lookup efficiently this can be slightly faster at runtime but incurs a startup penalty.
这篇关于最快的基本转换方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!