2014年4月10日木曜日

開発環境

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

その他参考書籍

実習 17-4.

コード(BBEdit, Emacs)

sample344_4_1.cpp

#include <cstring>

const int SIZE = 100000000;
char s[SIZE];

int main(int argc, char *argv[])
{
  int total = 0;
  char ch;
  int i;
  
  std::memset(s, 1, sizeof(s));

  for (i = 0; i < SIZE; ++i)
    for (ch = s[i]; ch != 0; ch <<= 1)
      if ((ch & 0x80) != 0)
        ++total;

  return (0);
}

前のコードからiとjも除去してみたコード。

sample344_4_2.cpp

#include <cstring>

const int SIZE = 100000000;
char s[SIZE];

int main(int argc, char *argv[])
{
  register int total = 0;
  register char ch;
  register int i;
  
  std::memset(s, 1, sizeof(s));

  for (i = 0; i < SIZE; ++i)
    for (ch = s[i]; ch != 0; ch <<= 1)
      if ((ch & 0x80) != 0)
        ++total;

  return (0);
}

Makefile

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

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

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

clean:
 rm sample344_4_1 sample344_4_2

入出力結果(Terminal)

$ make
g++ -g -Wall -o sample344_4_1 sample344_4_1.cpp
g++ -g -Wall -o sample344_4_2 sample344_4_2.cpp
$ time ./sample344_4_1

real 0m25.949s
user 0m12.244s
sys 0m0.361s
$ time ./sample344_4_2

real 0m18.476s
user 0m12.155s
sys 0m0.289s
$ 

0 コメント:

コメントを投稿