2014年4月7日月曜日

開発環境

C++実践プログラミング (スティーブ オウアルライン (著)、Steve Oualline (原著)、Steve Oualline(原著)、望月 康司(翻訳)、クイープ(翻訳) 、オライリー・ジャパン)のⅣ部(高度なプログラミング概念)の17章(デバッグと最適化)、17.12(プログラミング実習)、実習 17-2.を解いてみる。

その他参考書籍

実習 17-2.

コード(BBEdit, Emacs)

sample344_2_1.cpp

#include <cstring>

const int X_SIZE = 1000;
const int Y_SIZE = 1000;
int matrix1[X_SIZE][Y_SIZE];
int matrix2[Y_SIZE][X_SIZE];
int matrix3[X_SIZE][X_SIZE];

int main(int argc, char *argv[])
{
  int i;
  int j;
  int k;

  std::memset(matrix1, -1, sizeof(matrix1));
  std::memset(matrix2, -1, sizeof(matrix2));
  
  for (i = 0; i < X_SIZE; ++i)
    for (j = 0; j < X_SIZE; ++j) {
      matrix3[i][j] = 0;
      for (k = 0; k < Y_SIZE; ++k)
         matrix3[i][j] += matrix1[i][k] * matrix2[k][j];
    }
  
  return (0);
}

sample344_2_2.cpp

#include <cstring>

const int X_SIZE = 1000;
const int Y_SIZE = 1000;
int matrix1[X_SIZE][Y_SIZE];
int matrix2[Y_SIZE][X_SIZE];
int matrix3[X_SIZE][X_SIZE];

int main(int argc, char *argv[])
{
  int *matrix1_ptr;
  int *matrix2_ptr;
  int *matrix3_ptr;
  int i;
  int j;
  
  std::memset(matrix1, -1, sizeof(matrix1));
  std::memset(matrix2, -1, sizeof(matrix2));

  i = 0;
  j = 0;
  for (matrix3_ptr = &matrix3[0][0];
       matrix3_ptr <= &matrix3[X_SIZE - 1][X_SIZE - 1]; ++matrix3_ptr, ++j) {
    *matrix3_ptr = 0;
    for (matrix1_ptr = &matrix1[i][0], matrix2_ptr = &matrix2[0][j];
         matrix1_ptr <= &matrix1[i][Y_SIZE - 1];
         ++matrix1_ptr, matrix2_ptr += X_SIZE)
      *matrix3_ptr += *matrix1_ptr * *matrix2_ptr;
    if (j == X_SIZE - 1) {
      j = -1;
      ++i;
    }
  }
  
  return (0);
}

Makefile

#
# FSFのg++コンパイラ用のMakefile
#
CC=g++
CFLAGS=-g -Wall
all: sample344_2_1 sample344_2_2

sample344_2_1: sample344_2_1.cpp
 ${CC} ${CFLAGS} -o sample344_2_1 sample344_2_1.cpp

sample344_2_2: sample344_2_2.cpp
 ${CC} ${CFLAGS} -o sample344_2_2 sample344_2_2.cpp

clean:
 rm sample344_2_1 sample344_2_2

入出力結果(Terminal)

$ make
g++ -g -Wall -o sample344_2_1 sample344_2_1.cpp
g++ -g -Wall -o sample344_2_2 sample344_2_2.cpp
$ time ./sample344_2_1

real 1m12.679s
user 0m29.212s
sys 0m0.405s
$ time ./sample344_2_2

real 0m58.118s
user 0m28.650s
sys 0m0.394s
$

0 コメント:

コメントを投稿