13

任意のサイズの 2 つの整数を比較するための、かなり標準的な C (Linux) 関数、またはコード効率が良いがパフォーマンスの良いアプローチはありますか?

int intcmp(const void *a, const void *b, size_t size)整数ab実用的なサイズで機能するパラメーターを持つものを探していますsize。(memcmp()アーキテクチャがビッグエンディアンの場合はうまくいくと思います。)

私がよく使用する実装は次のようになります ( Efficient integer compare functionからの改善があります) が、完全に汎用的ではなく、コードのオーバーヘッドが十分にあるため、スロットに入れる前によく考えます。

int intcmp(const void *a, const void *b, size_t size) {

    #define CASE_SIZE_RETURN_A_B_CMP(_t) \
        case sizeof(_t): \
            return ((*(_t *)(a) > *(_t *)(b)) - (*(_t *)(a) < *(_t *)(b)))

    switch (size) {
    CASE_SIZE_RETURN_A_B_CMP(char);
    CASE_SIZE_RETURN_A_B_CMP(short);
    CASE_SIZE_RETURN_A_B_CMP(int);
    CASE_SIZE_RETURN_A_B_CMP(long long);
    }
    #undef CASE_SIZE_RETURN_A_B_CMP

    assert(0);
    return 0;
}
4

4 に答える 4

2

静的インライン関数には、引数が 1 回だけ評価されるという利点があります (これは、マクロでは難しい/不可能です)。これにより、次のような関数呼び出しが可能になりますint diff = cmp_all (p++, q++, sizeof *p);

#include <stdlib.h>
#include <stdint.h>

static inline int cmp1(const int8_t *one, const int8_t *two)
{
if (*one < *two) return -1;
else if (*one > *two) return 1;
else return 0;
}

static inline int cmp2(const int16_t *one, const int16_t *two)
{
if (*one < *two) return -1;
else if (*one > *two) return 1;
else return 0;
}

static inline int cmp4(const int32_t *one, const int32_t *two)
{
if (*one < *two) return -1;
else if (*one > *two) return 1;
else return 0;
}

static inline int cmp8(const int64_t *one, const int64_t *two)
{
if (*one < *two) return -1;
else if (*one > *two) return 1;
else return 0;
}

int cmp_all(const void *one, const void *two, size_t size)
{
switch(size) {
case 1: return cmp1(one, two);
case 2: return cmp2(one, two);
case 4: return cmp4(one, two);
case 8: return cmp8(one, two);
default: return 0; /* that will teach them ... */
        }
}
于 2013-05-26T10:18:04.907 に答える
0

以下のリンクが参考になると思います。コンパレータを使用せずに比較を行い、コードのオーバーヘッドを少し抑えます。私は過去にこのリンクに関連付けられたコードを自分で使用しました。

-グッドハンティング-

論理演算子を使用せずに整数を比較するCプログラム?

于 2013-05-13T14:56:27.050 に答える
0

呼び出しサイトに利用可能なサイズがある場合は、適切な関数をすぐに呼び出すために、そこのルックアップ テーブルのインデックスとして使用することをお勧めします。

于 2013-05-13T15:00:58.387 に答える