首页 >> PHP >> 内容页

PHP bitmap重叠时间过滤

场景:
计算所有设备的月故障率, 去除重叠的故障时间, 时间单位是秒。
如果直接用bool数组,按一个月30天算, 2592000秒 1个月消耗内存 150MB左右。
相同情况用bitmap只需18MB左右内存。
并可以判断值,减少计算数量。
目前公司项目,统计1年半, 只需耗时700毫秒。

class BitMap
{

  protected $data;
  public $size;
  protected $PHP_INT_BITS = PHP_INT_SIZE * 8;

  public function __construct(int $size)
  {

    $arr_size = $size / $this->PHP_INT_BITS;
    if ($size % $this->PHP_INT_BITS > 0) {
      $arr_size += 1;
    }

    $this->data = array_fill(0, $arr_size, 0);
    $this->size = $size;
  }

  public function countOnes()
  {
    $count = 0;
    foreach ($this->data as $block) {
      if ($block === 0) continue;
      for ($i = 0; $i < $this->PHP_INT_BITS; $i++) {
        if (($block & ($block << $i)) != 0) {
          $count += 1;
        }
      }
    }
    return $count;
  }

  public function setBit($pos)
  {
    $nArr = $pos / $this->PHP_INT_BITS;
    $nPos = $pos % $this->PHP_INT_BITS;

    $this->data[$nArr] |= (1 << $nPos);
  }
}