12
12

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.

Pythonの平方根どれが早いか

Last updated at Posted at 2019-09-28

はじめに

Pythonの平方根でどの方法が早いかを試しました。
計測方法が間違っていない場合、mathが一番早いです。
みんな兢プロでは、math.sqrt(n)を使おうな!
でもタイプ数や速度的に、n ** 0.5でもいいと思ってます。

追記: 環境によって速度の差異があるので、話半分に聞いてください。

環境

  • Google Colaboratory
  • Python 3.6.8

試した方法

  • n ** 0.5
  • pow(n, 0.5)
  • math.sqrt(n)
  • numpy.sqrt(n)
  • sympy.sqrt(n)
  • scipy.sqrt(n)

import math
import numpy as np
import sympy
import scipy

n = 12345678910

%timeit -r 3 -n 1000 n ** 0.5
# 1000 loops, best of 3: 136 ns per loop
%timeit -r 3 -n 1000 pow(n, 0.5)
# 1000 loops, best of 3: 183 ns per loop
%timeit -r 3 -n 1000 math.sqrt(n)
# 1000 loops, best of 3: 70.7 ns per loop
%timeit -r 3 -n 1000 np.sqrt(n)
# 1000 loops, best of 3: 930 ns per loop
%timeit -r 3 -n 1000 sympy.sqrt(n)
# 1000 loops, best of 3: 1.27 µs per loop
%timeit -r 3 -n 1000 int(scipy.sqrt(n))
# 1000 loops, best of 3: 7.7 µs per loop

テストコード

gist: sqrt.ipynb

12
12
4

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
12
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?