括弧でくくる: Sample 3: 応用2(C)

高速化プログラミング   
トップ  >  演算数と高速化  >  括弧でくくる  >  Sample 3: 応用2(C)

括弧でくくる: Sample 3: 応用2(C)

言語の変更:   FORTRAN版

■ 概要

このサンプルでは式(1)にしたがって配列a, b, cから配列xを計算します。式(1)では掛け算が4回、足し算が3回あります。このサンプルもきれいに因数分解できませんし、部分的な共通因子が二つあります。うまく括弧で共通因子をまとめられれば、掛け算は2回に減らせます。

u=xy+yz+zx           ... 式(1)

下の「回答例」ボタンをクリックすれば、式(2)に回答例が表示されます。興味がある方はクリックする前にぜひ考えてみてください。

          ... 式(2)

Code 1は式(1)によってコーディングしたものです。Code 2は式(2)によってコーディングしたものです。配列xとyのサイズnは10,000とします。計算時間が非常に短いので、より正確な計算時間を得るためにこの計算は100,000回まわします。

■ ソースコード


  ◆ Code 1   ◆ Code 2
 
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
  int i,j;
  int n = 10000, m = 100000;

  // Initialization
  double *a = new double[n];
  double *b = new double[n];
  double *c = new double[n];
  double *x = new double[n];
  for (i=0; i<n; i++) a[i] = rand();
  for (i=0; i<n; i++) b[i] = rand();
  for (i=0; i<n; i++) c[i] = rand();

  // Start time
  clock_t time0 = clock();

  // Main calculation
  for (j=0; j<m; j++)
    for (i=0; i<n; i++)
      x[i] = 1.0 + 2.0 * a[i] + a[i] * b[i] + a[i] * b[i] * c[i];

  // Finish time
  clock_t time1 = clock();

  // Output time
  double time = (double)(time1-time0)/CLOCKS_PER_SEC;
  printf("Time = %15.7f sec\n", time);

  delete[] a;
  delete[] b;
  delete[] c;
  delete[] x;
  return 0;
}

    
 
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
  int i,j;
  int n = 10000, m = 100000;

  // Initialization
  double *a = new double[n];
  double *b = new double[n];
  double *c = new double[n];
  double *x = new double[n];
  for (i=0; i<n; i++) a[i] = rand();
  for (i=0; i<n; i++) b[i] = rand();
  for (i=0; i<n; i++) c[i] = rand();

  // Start time
  clock_t time0 = clock();

  // Main calculation
  for (j=0; j<m; j++)
    for (i=0; i<n; i++)
      x[i] = 1.0 + a[i] * (2.0 + b[i] * (1.0 + c[i]));

  // Finish time
  clock_t time1 = clock();

  // Output time
  double time = (double)(time1-time0)/CLOCKS_PER_SEC;
  printf("Time = %15.7f sec\n", time);

  delete[] a;
  delete[] b;
  delete[] c;
  delete[] x;
  return 0;
}

    

■ 計算時間の測定結果

Code 1Code 2の計算時間の測定結果を表1に示します。ここではそれぞれのコードを5回実行して、平均とCode 1Code 2との計算時間の比率も表示します。

表1 計算時間の測定結果(単位: sec)
1回目 2回目 3回目 4回目 5回目 平均 倍率
Code 1 7.80 7.63 7.53 7.55 7.55 7.61 1.37
Code 2 5.57 5.54 5.54 5.52 5.54 5.54 -

■ 考察

Code 1Code 2に比べて掛け算が2回多いため、計算時間も1.37倍遅いという結果が得ました。



はじめに

演算数を減らす

メモリジャンプを減らす

高性能のアルゴリズム

その他



4 8 6 2 9 7