배열 동작을 벡터화

[책] 고성능 파이썬 중에서

배열을 이용한 코드와 벡터를 이용한 코드 예제

배열

import math

def check_prime(number):
  sqrt_number = math.sqrt(number)
  for i in range(2,int(sqrt_number)+1):     
    if (number/i).is_integer():      
      return False
  return True
%time print(f"check_prime(10,000,000) = {check_prime(10_000_000)}")
%time print(f"check_prime(10,000,019) = {check_prime(10_000_019)}")
# 결과
check_prime(10,000,000) = False
CPU times: user 135 µs, sys: 0 ns, total: 135 µs
Wall time: 90.6 µs
check_prime(10,000,019) = True
CPU times: user 60 µs, sys: 0 ns, total: 60 µs
Wall time: 64.8 µs

벡터

import numpy as np
import math

def my_is_integer(numbers):
  temp = numbers.astype(np.int32)
  return numbers<=temp

# 벡터화
def check_prime_vector(number):
  numbers=np.array(range(2,int(math.sqrt(number)+1)))
  for i in range(0, len(numbers), 5):    
    result = (number/numbers[i:(i+5)])    
    result = my_is_integer(result)
    if(any(result)):
      return False
  return True
%time print(f"check_prime(10,000,000) = {check_prime_vector(10_000_000)}")
%time print(f"check_prime(10,000,019) = {check_prime_vector(10_000_019)}")
# 결과
check_prime(10,000,000) = False
CPU times: user 120 µs, sys: 0 ns, total: 120 µs
Wall time: 152 µs
check_prime(10,000,019) = True
CPU times: user 116 µs, sys: 0 ns, total: 116 µs
Wall time: 122 µs

좋은 웹페이지 즐겨찾기