4

私はスレッドプログラミングが初めてで、概念的な問題があります。クラスのプロジェクトとして行列乗算を行っています。ただし、スレッドを使用せずに実行し、スレッドを使用して回答行列の各セルのスカラー積を計算し、最初の行列を比率に分割して、各スレッドが計算する部分が等しくなるようにします。私の問題は、スカラー積の実装が非常に迅速に終了することです。これは私が期待することですが、3 番目の実装では、スレッド化されていない実装よりもはるかに高速に答えが計算されません。たとえば、2 つのスレッドを使用する場合、行列の両方の半分を同時に処理できるため、約半分の時間で計算されますが、まったくそうではありません。3 番目の実装に問題があるように感じますが、そうではありません。並列に動作するとは思わないので、コードを以下に示します。誰かがこれについて私をまっすぐに設定できますか? すべてのコードが質問に関連しているわけではありませんが、問題がローカルではない場合に備えて含めました。ありがとう、

主なプログラム:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include<fstream>
#include<string>
#include<sstream>

#include <matrix.h>
#include <timer.h>
#include <random_generator2.h>

const float averager=2.0; //used to find the average of the time taken to multiply the matrices.

//Precondition: The matrix has been manipulated in some way and is ready to output the statistics
//Outputs the size of the matrix along with the user elapsed time.
//Postconidition: The stats are outputted to the file that is specified with the number of threads used
//file name example: "Nonparrallel2.dat"
void output(string file, int numThreads , long double time, int n);

//argv[1] = the size of the matrix
//argv[2] = the number of threads to be used.
//argv[3] = 
int main(int argc, char* argv[])
{ 
  random_generator rg;
  timer t, nonparallel, scalar, variant;
  int n, total = 0, numThreads = 0;
  long double totalNonP = 0, totalScalar = 0, totalVar = 0;

  n = 100;

/*
 * check arguments
 */
      n = atoi(argv[1]);
      n = (n < 1) ? 1 : n;
      numThreads = atoi(argv[2]);
/*
 * allocated and generate random strings
 */
  int** C;
  int** A;
  int** B;

  cout << "**NOW STARTING ANALYSIS FOR " << n << " X " << n << " MATRICES WITH " << numThreads << "!**"<< endl;

  for (int timesThrough = 0; timesThrough < averager; timesThrough++)
  {

      cout << "Creating the matrices." << endl;
      t.start();
      C = create_matrix(n);
      A = create_random_matrix(n, rg);
      B = create_random_matrix(n, rg);
      t.stop();

      cout << "Timer (generate): " << t << endl;

        //---------------------------------------------------------Ends non parallel-----------------------------
        /*
         * run algorithms
         */
          cout << "Running non-parallel matrix multiplication: " << endl;
          nonparallel.start();
          multiply(C, A, B, n);
          nonparallel.stop();
        //-----------------------------------------Ends non parallel----------------------------------------------


        //cout << "The correct matrix" <<endl;
        //output_matrix(C, n);

          cout << "Timer (multiplication): " << nonparallel << endl;
          totalNonP += nonparallel.user();


          //D is the transpose of B so that the p_scalarproduct function does not have to be rewritten
          int** D = create_matrix(n); 
          for (int i = 0; i < n; i++)
            for(int j = 0; j < n; j++)
                D[i][j] = B[j][i];
        //---------------------------------------------------Start Threaded Scalar Poduct--------------------------
          cout << "Running scalar product in parallel" << endl;
          scalar.start();
          //Does the scalar product in parallel to multiply the two matrices.
          for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++){
            C[i][j] = 0;
            C[i][j] = p_scalarproduct(A[i],D[j],n,numThreads);
            }//ends the for loop with j
          scalar.stop();

          cout << "Timer (scalar product in parallel): " << scalar << endl;
          totalScalar += scalar.user();
        //---------------------------------------------------Ends Threaded Scalar Poduct------------------------


        //---------------------------------------------------Starts Threaded Variant For Loop---------------
           cout << "Running the variation on the for loop." << endl;
            boost :: thread** thrds;


            //create threads and bind to p_variantforloop_t
            thrds = new boost::thread*[numThreads];

            variant.start();
            for (int i = 1; i <= numThreads; i++)
                thrds[i-1] = new boost::thread(boost::bind(&p_variantforloop_t, 
                        C, A, B, ((i)*n - n)/numThreads ,(i * n)/numThreads, numThreads, n));   
cout << "before join" <<endl;
            // join threads 
              for (int i = 0; i < numThreads; i++)
            thrds[i]->join();
             variant.stop();

            // cleanup 
              for (int i = 0; i < numThreads; i++)
            delete thrds[i];
              delete[] thrds;

        cout << "Timer (variation of for loop): " << variant <<endl;
        totalVar += variant.user();
        //---------------------------------------------------Ends Threaded Variant For Loop------------------------

         // output_matrix(A, n);
         // output_matrix(B, n);
         //   output_matrix(E,n);

        /*
         * free allocated storage
         */

        cout << "Deleting Storage" <<endl;

          delete_matrix(A, n);
          delete_matrix(B, n);
          delete_matrix(C, n);
          delete_matrix(D, n);  

        //avoids dangling pointers
          A = NULL;
          B = NULL;
          C = NULL;
          D = NULL;
  }//ends the timesThrough for loop   

  //output the results to .dat files
  output("Nonparallel", numThreads, (totalNonP / averager) , n);
  output("Scalar", numThreads, (totalScalar / averager), n);
  output("Variant", numThreads, (totalVar / averager), n);

  cout << "Nonparallel = " << (totalNonP / averager) << endl;
  cout << "Scalar = " << (totalScalar / averager) << endl;
  cout << "Variant = " << (totalVar / averager) << endl;

  return 0;
}

void output(string file, int numThreads , long double time, int n)
{
    ofstream dataFile;
    stringstream ss;

    ss << numThreads;
    file += ss.str();
    file += ".dat";

    dataFile.open(file.c_str(), ios::app);
    if(dataFile.fail())
    {
        cout << "The output file didn't open." << endl;
        exit(1);
    }//ends the if statement.
    dataFile << n << "     " << time << endl;
    dataFile.close();
}//ends optimalOutput function

マトリックス ファイル:

#include <matrix.h>
#include <stdlib.h>

using namespace std;

int** create_matrix(int n)
{
  int** matrix;

  if (n < 1) 
    return 0;

  matrix = new int*[n];
  for (int i = 0; i < n; i++)
    matrix[i] = new int[n];

  return matrix;
}

int** create_random_matrix(int n, random_generator& rg)
{
  int** matrix;

  if (n < 1) 
    return 0;

  matrix = new int*[n];
  for (int i = 0; i < n; i++)
    {
      matrix[i] = new int[n];
      for (int j = 0; j < n; j++)
    //rg >> matrix[i][j];
    matrix[i][j] = rand() % 100;
    }

  return matrix;
}

void delete_matrix(int** matrix, int n)
{ 
    for (int i = 0; i < n; i++) 
      delete[] matrix[i];

    delete[] matrix;

    //avoids dangling pointers.
    matrix = NULL;
}

/*
 * non-parallel matrix multiplication
 */
void multiply(int** C, int** A, int** B, int n)
{ 
  if ((C == A) || (C == B))
    { 
      cout << "ERROR: C equals A or B!" << endl;
      return;
    }

  for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
      {
    C[i][j] = 0;
    for (int k = 0; k < n; k++)
      C[i][j] += A[i][k] * B[k][j];
     }
} 

void p_scalarproduct_t(int* c, int* a, int* b, 
                   int s, int e, boost::mutex* lock)
{ 
  int tmp;

  tmp = 0;
  for (int k = s; k < e; k++){
    tmp += a[k] * b[k];
//cout << "a[k]= "<<a[k]<<"b[k]= "<< b[k] <<"    "<<k<<endl;
}
  lock->lock();
  *c = *c + tmp;
  lock->unlock();
} 

int p_scalarproduct(int* a, int* b, int n, int m)
{ 
  int c;
  boost::mutex lock;
  boost::thread** thrds;

  c = 0;

/* create threads and bind to p_merge_sort_t */
  thrds = new boost::thread*[m];
  for (int i = 0; i < m; i++)
    thrds[i] = new boost::thread(boost::bind(&p_scalarproduct_t, 
                             &c, a, b, i*n/m, (i+1)*n/m, &lock));
/* join threads */
  for (int i = 0; i < m; i++)
    thrds[i]->join();

/* cleanup */
  for (int i = 0; i < m; i++)
    delete thrds[i];
  delete[] thrds;

  return c;
} 

void output_matrix(int** matrix, int n)
{ 
  cout << "[";
  for (int i = 0; i < n; i++)
    {
      cout << "[ ";
      for (int j = 0; j < n; j++)
    cout << matrix[i][j] << " ";
      cout << "]" << endl;
    }
  cout << "]" << endl;
}





void p_variantforloop_t(int** C, int** A, int** B, int s, int e, int numThreads, int n)
{
//cout << "s= " <<s<<endl<< "e= " << e << endl;
    for(int i = s; i < e; i++)
        for(int j = 0; j < n; j++){
          C[i][j] = 0;
//cout << "i " << i << "  j " << j << endl;
          for (int k = 0; k < n; k++){
            C[i][j] += A[i][k] * B[k][j];}
        }
}//ends the function
4

2 に答える 2

3

私の推測では、あなたはFalse Sharingに遭遇していると思います。でローカル変数を使用してみてくださいp_variantforloop_t:

void p_variantforloop_t(int** C, int** A, int** B, int s, int e, int numThreads, int n)
{
    for(int i = s; i < e; i++)
        for(int j = 0; j < n; j++){
          int accu = 0;
          for (int k = 0; k < n; k++)
            accu += A[i][k] * B[k][j];
          C[i][j] = accu;
        }
}
于 2011-05-01T19:43:19.290 に答える
0

コメントでの回答に基づいて、理論的には、単一のスレッド (つまり、CPU) しか使用できないため、スレッド管理のオーバーヘッドのために、すべてのスレッド化されたバージョンはシングルスレッド化されたバージョンと同じ時間またはそれより長くなるはずです。行列の一部を解決するために取られたタイム スライスは、別の並列タスクから盗まれたタイム スライスであるため、スピードアップはまったく見られないはずです。単一の CPU では、CPU のリソースを時分割で共有するだけです。特定の 1 つの時間内で実際に並行して作業を行うことはありません。2番目の実装がより速く実行される理由は、内部ループでのポインターの逆参照とメモリアクセスが少ないためだと思います。たとえば、 と のC[i][j] += A[i][k] * B[k][j];両方からの主な操作ではmultiplyp_variantforloop_t、アセンブリレベルで多くの操作を見ていますが、その多くはメモリ関連です。「アセンブリ疑似コード」では次のようになります。

1)Aスタック上の によって参照されるアドレスからレジスターにポインター値を移動します。 2 )変数、、またはによって参照されるスタック外の値によって、R1
レジスター内のアドレスをインクリメントします 。変数、、またはによって参照されるスタックからの値によって アドレスをインクリメントします 。レジスタへのスタック(したがって、 の値を保持します)R1ijk
R1R1
R1ijk
R1R1R1A[i][k]
BR2R2B[k][j]
7)Cスタック上の によって参照されるアドレスに対してステップ 1 ~ 4 を実行し、レジスタに入れます。R3
8) が指すアドレスから値を移動しますR3(R4つまり、R4実際の値を に保持しますC[i][j]) 。 9) レジスタを
乗算し、レジスタに格納します。 10) 加算します。 11) からの最終値を、が指すメモリアドレスに戻します (最終結果が得られます) 。R1R2R5
R4R5R4
R4R3C[i][j]

これは、使用する汎用レジスタが 5 つあり、コンパイラがそれらを利用するために C コードを適切に最適化したと仮定した場合です。ループ インデックス変数ij、およびkスタック上にあるため、それらにアクセスするには、レジスターにある場合よりもさらに時間がかかります...それは、コンパイラーがプラットフォームで何個のレジスターを使用する必要があるかによって異なります。さらに、最適化を行わずにコンパイルした場合、スタック外でより多くのメモリ アクセスを行う可能性があります。これらの一時値の一部は、レジスタではなくスタックに格納され、スタック外で再アクセスされるため、さらに時間がかかります。レジスタ間で値を移動するよりも。いずれにせよ、上記のコードは最適化がはるかに困難です。これは機能しますが、32 ビット x86 プラットフォームを使用している場合は、それほど多くの汎用レジスタを使用することはできません (ただし、少なくとも 6 つある必要があります)。x86_64 にはより多くのレジスタがありますが、それでも競合するすべてのメモリ アクセスがあります。

一方、タイトな内部ループ内のtmp += a[k] * b[k]fromのような操作p_scalarproduct_tは、はるかに高速に移動します...これは、アセンブリ擬似コードでの上記の操作です。

ループには小さな初期化ステップがあります

1)スタック変数ではなくtmpレジスタを作成し、その値を 0 に初期化します 2)スタック上で 参照されるアドレス値を移動します3) スタック外 の値を追加し、結果のアドレスをに保存します 4) 参照されるアドレス値を移動しますスタック上で5 ) スタック外 の値を追加し、結果のアドレスを 6に保存します。R1
aR2
sR2R2
bR3
sR3R3
R6e - s

1 回の初期化の後、実際の内部ループを開始します。

7) が指すアドレスの値を に移動R2するR4
8) が指すアドレスの値を に移動するR39 R5
) 乗算R4R5、その結果をR5
10に格納する 11) カウンタをインクリメントR5し、 12) カウンタを減算するゼロになるまで、そこでループを終了しますR1R1
R2R3
R6

これがコンパイラがこのループを設定する方法とまったく同じであることを保証することはできませんが、スカラーの例では一般に、必要な内部ループのステップが少なく、さらに重要なことにメモリアクセスが少ないことがわかります。したがって、メモリ位置を含み、レジスタのみの操作よりもはるかに遅いメモリフェッチを必要とする操作ではなく、レジスタのみを使用する操作でより多くのことを実行できます。したがって、一般的には、はるかに高速に移動しますが、それはスレッドとは関係ありません。

最後に、スカラー積の入れ子になったループが 2 つしかないことに気付きました。そのため、複雑さは O(N^2) ですが、他の 2 つの方法では、O(N^3) の複雑さに対して 3 つの入れ子になったループがあります。それによっても違いが出てきます。

于 2011-05-01T23:07:09.103 に答える