namarecoの負荷改善

  • 背景
    • 元々namareco-0.1.x時代のCPU負荷は20-30%@266MHzマシン
    • 現在は80-100%
    • 以前取ったprofileに引き続き今回は目視でソース上の無駄を確認してみた
  • 注目したソース
    • 改変した記憶のあるrtmp.rb:read()
  def read(len)
    tmpbuf = ''
    while len > 0
      if @offset + len <= @outbuf.size
        t = @offset
        @offset += len
        tmpbuf << @outbuf[t, len]
        len = 0
      else
        rem = @outbuf.size - @offset
        tmpbuf << @outbuf[@offset, rem]
        len -= rem
        begin
          timeout(READTIMEOUT) {
            @sock.readpartial(BUFSIZE, @outbuf)
          }
        rescue Timeout::Error
          @live_queue.push(RETRY_LIVE)
          Thread.exit
        rescue
          $log.fatal('[RTMP]: ' + $!)
          raise
        end
        @offset = 0

        @read_bytes += BUFSIZE
        $log.debug('[RTMP]: read_bytes: ' + @read_bytes.to_s)
        if (@read_bytes > @read_bytes_sent + @client_bw / 2)
          send_bytes_received
        end
      end
    end
    return tmpbuf
  end
    • 改善点(効果の大きかったものから)
      1. timeout()をselectに書き換えてみた
      2. @client_bw / 2の処理をループの外側に持っていった
  • 結果
    • 従来と同様のCPU負荷まで下がった
  • 考察
    • timeoutは新たにthreadを生成するのでスレッド切り替えオーバヘッドが馬・鹿にならないようだ
    • IOの待ち時間を適当に設定する場合はselectを利用するとよさそう
      • もっと正しいやり方があるのかもしれないが調べつくせなかった
    • 現在のタイムアウト時間は30秒に設定しているがもっと長めに設定した方がよいかも
      • いわゆる13Bytes病てもしかしてこれのせい?