忍者ブログ
適当に調べたことを適当に書きます。
[6] [5] [4] [3] [2] [1]
×

[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。

最近ではmemcachedなどが持て囃されているが、共有メモリもなかなか扱いやすい。
memcachedと違うところはIDにstringではなくintが必要なところでしょうか。
また、cache_limitのような設定もない。

今回は共有メモリ関数、shmopを使って簡単なカウンターを作ってみた。

カウンタープログラム
カウンタークラス
カウンタークラス(ファイル版)

簡単にファイル版も作成して比べたところでは倍ほど早くなるようだ。
思ったよりは遅かった。

#当然メモリなのでどこかでファイル保存させる処理が必要になる。

tmpデータやsessionデータなど、上手く使えば高速で簡単な処理が可能になりそう?

ちなみにこのshmop系はデフォルトでは使えない。
コンフィギュアオプションを設定する必要がある。(PHP5.2.x)

<?php

class counter {

 private $size;
 public  $a_error;
 public  $o_shm;
 private $count;

 public function __construct() {
  $this->size = 100;
  $this->count = 0;
  $this->a_error = array();
 }

 public function __destruct() {
  if ($this->o_shm) {
   shmop_close($this->o_shm);
  }
 }

 public function count($id) {
  $this->connect($id, 'c');
  $this->count = $this->read();

  $this->count++;
  $this->write($this->count);
 }

 public function connect($id, $flg='c') {
  $this->o_shm = shmop_open($id, $flg, 0644, $this->size);
  if (!$this->o_shm) {
      $this->_setError('共有メモリセグメントを作成できませんでした。');
  }
 }

 public function is_error() {
  return (count($this->a_error)) ? $this->a_error : FALSE;
 }

 public function read($id='', $flg='') {
  $this->_checkObj($id, $flg);
  return sprintf("%d",shmop_read($this->o_shm, 0, $this->size));
 }

 public function write($data, $id='') {
  $this->_checkObj($id);
  $_len = strlen($data);
  if ($_len > $this->size) {
   $this->_setError('データサイズが大きすぎます。');
   return;
  }

  $new_len = shmop_write($this->o_shm, $data, 0);
  if ($new_len != $_len) {
      $this->_setError('データ全体を書き込めませんでした。');
  }
 }

 public function getCount() {
  return $this->count;
 }

 private function _checkObj($id) {
  if (!$this->o_shm && $id) {
   $this->connect($id, $flg);
  }
 }

 private function _setError($str) {
  $this->error[] = $str;
 }
}

PR

コメント


コメントフォーム
お名前
タイトル
文字色
メールアドレス
URL
コメント
パスワード
  Vodafone絵文字 i-mode絵文字 Ezweb絵文字


トラックバック
この記事にトラックバックする:


忍者ブログ [PR]
カレンダー
06 2025/07 08
S M T W T F S
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
フリーエリア
最新コメント
最新トラックバック
プロフィール
性別:
非公開
バーコード
ブログ内検索