c++ - 单词大写的最快方法

标签 c++ boost stdstring

使用 C++ 将单词 (std::string) 大写的最快方法是什么?

在使用带有 -O3 标志的 g++ 4.6.3 的 Debian Linux 上,这个使用 boost::to_lower 的函数将在大约 24 秒内在 AMD Phenom( tm) II X6 1090T 处理器 (3200 MHz)。

void Capitalize( std::string& word )
{
    boost::to_lower( word );
    word[0] = toupper( word[0] );
}

这个使用 std::transform 的函数在大约 10 秒内完成同样的事情。我在测试之间清除了 VM,所以我不认为这种差异是侥幸:

sync && echo 3 >/proc/sys/vm/drop_caches

void Capitalize( std::string& word )
{
    std::transform(word.begin(), word.end(), word.begin(), ::tolower);
    word[0] = toupper( word[0] );
}

有没有更快的方法?我不想为了速度而失去可移植性,但如果有更快的方法可以在 std C++ 或带有 boost 的 std C++ 中工作,我想尝试一下。

谢谢。

最佳答案

在处理不能保证输入为大写的 DNA 序列时,有这个确切的问题,并且 boost::to_upper 是代码中的瓶颈。更改为:

template<typename T_it>
void SequenceToUpperCase( T_it begin, T_it end )
{
    // Convert to upper: clear the '32' bit, 0x20 in hex. And with the
    // inverted bit string (~).
    for ( auto it = begin; it != end; ++it )
        *it &= ~0x20;
}

导致速度大幅 boost 。我确信可以通过例如进一步优化一次翻转 8 个字节,但使用上面的代码,大写对我们来说几乎是瞬时的。对于小写:做:

        *it |= 0x20;

关于c++ - 单词大写的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10688831/

相关文章:

C++定义和实例化有什么区别?

c++ - Boost 图的自定义 InputIterator (BGL)

c++ - Boost 计划选项示例

linux - 将缓冲区或 C 字符串复制到 std::string 的最快方法

c++ - 为什么 std::string 没有(明确的)const char* cast

c++ - Boost.Pointer 容器在 C++11/14 中被 std::unique_ptr 淘汰了吗?

c++ - 使用流将对象转换为字符串

c++ - Template类拷贝构造函数的写法

boost - Nix boost 安装遗漏标题

c++ - std::string - 从头到尾获取数据