10

GMP は、mpz_t を初期化して割り当てるためのメソッドを提供します。

mpz_init_set(a, b) を呼び出すと、b の内容が a に割り当てられます。ただし、これはbでディープコピーを実行すると思います。

私のプロジェクトでは、5,000,000 (640MB のメモリについて話している) の mpz_t の配列を操作する必要があり、使用しているフレームワークはそのような型に対してさまざまな割り当て操作を実行します (私はフレームワークを開発して書き直していません)。オプションではありません)。最近、ほとんどの代入後に b の値がクリアされるので、既に使用できる値をそのままディープ コピーするのは不自然に思えることに気付きました。ただし、フレームワークのインターフェイスではそれが許可されておらず (mpz_t のラッパーを使用)、それを変更するには多大な労力が必要です (いくつかの基本的なことはまだ変更できます)。

mpz_class へのポインターに基づくソリューションを既に試しましたが、驚くべきことに、パフォーマンスがまったく向上しません。実際、実行が遅くなります (ただし、巨大な配列ではテストされていません)。

私の質問は: mpz_t を浅いコピーできますか? 以下に例を示します

class somewrapper
{
    mpz_t v;
    somewrapper(mpz_t x)    //constructor: probably performing deep copy here as well
    {
        // the following line performs a deep copy(?) on x
        // but x is not used. why not shallow copy it?
        mpz_init_set(v, x);
    }
    somefunction() { }
}
4

1 に答える 1

1

Consider that mpz_t is a struct defined in gmp.h:

typedef struct
{
  int _mp_alloc;        /* Number of *limbs* allocated and pointed to by the _mp_d field.  */
  int _mp_size;         /* abs(_mp_size) is the number of limbs the last field points to.  If _mp_size is negative this is a negative number.  */
  mp_limb_t *_mp_d;     /* Pointer to the limbs.  */
} __mpz_struct;

// ... 

typedef __mpz_struct mpz_t[1];

where the GMP developers cast the type as an array of size one because this simplifies passing the type to functions just as if it was a pointer (see here for a fine explanation)

So you can make a shallow copy of an mpz_t like this:

class somewrapper
{
    mpz_t v;
    somewrapper(mpz_t x)    //constructor: for sure passing the reference
    {
        // the following line performs a shallow copy
        v->_mp_alloc = x->_mp_alloc;
        v->_mp_size = x->_mp_size;
        v->_mp_d = x->_mp_d;
    }
    somefunction() { }
}

but note that if you delete the original mpz before deleting the shallow copy, say using mpz_clear, then the juice in mp_limb_t *_mp_d will be gone, and the pointer in the shallow copy will no longer be valid so accessing it may cause trouble.

于 2021-12-19T01:35:47.113 に答える