使用整数模板参数时,可以展开一个循环吗? [英] Can one unroll a loop when working with an integer template parameter?

查看:53
本文介绍了使用整数模板参数时,可以展开一个循环吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

template <int size>
inline uint hashfn( const char* pStr )
{
   uint result = *pStr;
   switch ( size )
   {
      case 10:
         result *= 4;
         result += *pStr;
      case 9:
         result *= 4;
         result += *pStr;
      ...
      ...
      case 2:
         result *= 4;
         result += *pStr;
   }
   return result;
}

此代码是某些长度的DNA序列的哈希函数,其中长度是模板参数.这是一个带有switch语句的展开循环,可在正确的位置跳转. 但是大小是一个常数,因为它是模板参数. 我可以专门针对某些尺寸值吗? 也许像这样:

This code is a hash function for DNA sequences of certain lenghts where the length is a template parameter. It is an unrolled loop with a switch statement to jump in at the right spot. The size is however a constant since it is a template parameter. Could I specialize this for certain size values? Maybe with something like:

template <int 2>
inline uint hashfn( const char* pStr )
{
  uint result = *pStr;
  result *= 4;
  ++pStr;
  result += *pStr;
  return result;
}

推荐答案

我倾向于使用模板递归地进行操作.

I would tend to do it recursively with templates.

例如:

template<class TOp,int factor>
struct recursive_unroll {
    __forceinline static void result( TOp& k ) {
        k();
        recursive_unroll<TOp,factor-1>::result( k );
    }
};

template<class TOp>
struct recursive_unroll<TOp,0> {
    __forceinline static void result( TOp& k ) {}
};


struct  op    {
    op( const char* s ) : res( 0 ), pStr( s )   {}

    unsigned int res;
    const char* pStr;        
    __forceinline void  operator()()  {
        res *= 4;
        res += *pStr;
        ++pStr;
        //std::cout << res << std::endl;
    }
};

char str[] = "dasjlfkhaskjfdhkljhsdaru899weiu";

int _tmain(int argc, _TCHAR* argv[])
{
    op tmp( str );
    recursive_unroll<op,sizeof( str ) >::result( tmp );
    std::cout << tmp.res << std::endl;
    return 0;
}

这会为我生成最佳代码.如果没有 __ forceinline ,则无法正确内联代码.

This produces optimal code for me. Without __forceinline the code is not properly inlined.

在使用此类优化之前,您应该始终对代码进行测试.然后,您应该查看程序集并解密编译器已经为您完成的工作.但是在这种情况下,(对我而言)似乎有所助益.

You should always bench your code before using such optimizations. And then you should look at the assembly and decipher what your compiler already does for you. But in this case, it seems to be an boost (for me).

__ forceinline 是Microsoft Visual Studio特定的扩展.编译器应生成最佳代码,但并非如此.所以在这里我用了这个扩展名.

__forceinline is a Microsoft Visual Studio specific extension. The compiler should generate optimal code, but for this it doesn't. So here I used this extension.

这篇关于使用整数模板参数时,可以展开一个循环吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆