2014年4月11日金曜日

開発環境

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

その他参考書籍

実習 17-5.

コード(BBEdit, Emacs)

sample344_5_1.cpp

#include <cstring>

const int X_SIZE = 10000000;
const int Y_SIZE = 10;

int matrix_src[X_SIZE][Y_SIZE];
int matrix_dst[X_SIZE][Y_SIZE];

void copy_matrix()
{
  int i;
  int j;
  for (i = 0; i < X_SIZE; ++i)
    for (j = 0; j < Y_SIZE; ++j)
      matrix_dst[i][j] = matrix_src[i][j];
}

int main(int argc, char *argv[])
{
  std::memset(matrix_src, -1, sizeof(matrix_src));
  copy_matrix();
  return (0);
}

sample344_5_2.cpp

#include <cstring>

const int X_SIZE = 10000000;
const int Y_SIZE = 10;

int matrix_src[X_SIZE][Y_SIZE];
int matrix_dst[X_SIZE][Y_SIZE];

inline void copy_matrix()
{
  int *matrix_src_ptr;
  int *matrix_dst_ptr;
  
  matrix_src_ptr = &matrix_src[0][0];
  matrix_dst_ptr = &matrix_dst[0][0];
  for (; matrix_src_ptr <= &matrix_src[X_SIZE - 1][Y_SIZE - 1];
       ++matrix_src_ptr, ++matrix_dst_ptr)
    *matrix_dst_ptr = *matrix_src_ptr;
}

int main(int argc, char *argv[])
{
  std::memset(matrix_src, -1, sizeof(matrix_src));
  copy_matrix();
  return (0);
}

sample344_5_3.cpp

#include <cstring>

const int X_SIZE = 10000000;
const int Y_SIZE = 10;

int matrix_src[X_SIZE][Y_SIZE];
int matrix_dst[X_SIZE][Y_SIZE];

int main(int argc, char *argv[])
{
  std::memset(matrix_src, -1, sizeof(matrix_src));
  std::memcpy(matrix_dst, matrix_src, sizeof(matrix_src));
  return (0);
}

Makefile

#
# FSFのg++コンパイラ用のMakefile
#
CC=g++
CFLAGS=-g -Wall
all: sample344_5_1 sample344_5_2 sample344_5_3

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

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

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

clean:
 rm sample344_5_1 sample344_5_2 sample344_5_3

入出力結果(Terminal)

$ make
g++ -g -Wall -o sample344_5_1 sample344_5_1.cpp
g++ -g -Wall -o sample344_5_2 sample344_5_2.cpp
g++ -g -Wall -o sample344_5_3 sample344_5_3.cpp
$ time ./sample344_5_1

real 0m4.571s
user 0m1.146s
sys 0m1.022s
$ time ./sample344_5_2

real 0m4.019s
user 0m0.835s
sys 0m1.000s
$ time ./sample344_5_3

real 0m2.131s
user 0m0.526s
sys 0m0.934s
$ 

0 コメント:

コメントを投稿