7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

NVectorはVectorの80倍速い

Posted at

rubyにはベクトルを扱うための、Vectorクラスがあります。Vectorクラスはrubyで実装されているので、正直遅いです。そこで、拡張配列クラスNArrayに含まれるNVectorを使ってみました。NArrayはCで実行されるので、すごく早いはずです。

速度比較:ベクトルの内積を求める

"1" もしくは "0"からなる要素数5000000のベクトルを2つ生成し、二つのベクトルの内積を求めるまでの時間を計測します。

Vectorクラスの場合

# coding: utf-8

require 'matrix'

arrayA = []
arrayB = []

5000000.times do |n|
  arrayA << rand(2)
  arrayB << rand(2)
end

vectorA = Vector.elements(arrayA)
vectorB = Vector.elements(arrayB)

t = Time.now

p vectorA.inner_product(vectorB)

p Time.now - t

結果: 0.86 秒(862 ms)

NVectorの場合

# coding: utf-8

require "narray"

vectorA = NVector.int(5000000)
vectorB = NVector.int(5000000)

5000000.times do |n|
  vectorA[n] = rand(2)
  vectorB[n] = rand(2)
end

t = Time.now

p vectorA * vectorB

p Time.now - t

結果: 0.011 秒(10.6 ms)

処理の内容次第だとは思いますが、今回は約80倍の速度差が出ました(当然ですが・・・)。

7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?