728x90
728x90
728x90

빠른 이유로는 3가지 이유가 있다.

1. numpy.ndarray는 a collection of similar data-types that are densely packed in memory.

(반면, list는 different data-types을 가질 수 있고 computation하는 데에 있어서 몇가지 과정을 더 타야한다.)

(이 부분은 하단의 설명을 다시 보자.)

2. numpy는 한 task를 subtask로 알아서 나눠서 parallely하게 작동하기도 한다.

(예를 들면, np.dot()을 수행할 때, argument의 size가 크면 cpu core 전부를 쓰는 것을 확인할 수 있다.)

3. numpy는 C언어로 구현되어 있어서 더 빠르게 작동한다.

 

 

하늘색이 실제 저장된 값

ndarray는 element조회시 "data"에 접근 후, 모든 데이터를 쭉 접근 가능

쭉이란, 각 값들이 메모리에 연속적으로 저장되어 있음

게다가 각 element가 같은 dtype이라, +N byte형태로 빠른 element 연속 접근이 가능

 

list의 경우 각 파란색 값이 메모리에 연속적으로 존재하지 않음

ob_item 내에 각 element의 reference(메모리 주소)를 갖고 있다.

그 reference를 타고 가더라도, 객체 자체가 있고, 그 객체 내에 ob_digit(객체가 int라면)로 가야 element에 접근

즉, 접근단계가 ndarray(1)에 비해 list(3)가 접근 단계가 많다.

그리고 next element에 접근할 때도 ndarray(1)인데 list(3)이므로 접근 방식 자체에서 느린 구조이다.

 

결론

ndarray는

dtype이 similar한 녀석들로 만들면 고속 접근이 가능

 

list는

dtype이 different하더라도 담을 수가 있음, 따라서 무한한 정수가 가능(담긴 element int가 아무리 커져도 int32 형태로 제한이 걸릴 일은 없다는 것)

 

 

참고자료:

towardsdatascience.com/how-fast-numpy-really-is-e9111df44347

 

How Fast Numpy Really is and Why?

A comparison with standard Python Lists.

towardsdatascience.com

spyhce.com/blog/cpython-data-structures

 

CPython data structures | Spyhce blog

In this article we have a look at the underlying C implementation, how these types work and what tweaks are there to make them faster. Learn more!

spyhce.com

www.youtube.com/watch?v=fiYD0yCou4k

 

728x90
728x90

배경:

우리가 어떤 class의 object를 만들 때면, 각 object마다 dictionary가 할당되는데, 이는 object의 attribute를 저장해두기 위함이다. 이는 dictionary다 보니까 메모리를 꽤나 차지한다. 다수의 object를 만들 때면 이러한 메모리들이 쌓여 태산이 된다.

 

사용할 상황:

class에 attibutes가 제한되어 있다면(즉 향후에 dynamic하게 attributes를 추가하거나 하는 작업이 없다면)

__slots__로 attribute를 제한하고 시작하고, 이렇게 되면 dictionary를 사용하지 않아 메모리를 절약함과 동시에

attribute 접근 속도도 빨라진다.

 

사용법:

class attribute로 __slots__ = ['att1', 'att2'] 형태로, 사용할 attributes를 선언하면,

이 class의 object는 __dict__를 갖지 않는다.

 

장점:

-object의 attribute 접근 속도 향상

-메모리 절약

 

단점:

-dynamic attribute 할당은 불가

 

 

참고자료:

www.geeksforgeeks.org/python-use-of-__slots__/

 

Python | Use of __slots__ - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

728x90
728x90

dictionary의 값을 한번 조회하고 그 이후에 필요없다면 pop method를 사용하자.

(자꾸 get이나 dict[key]만 사용하려고함)

 

 

 

element가 sequence에 존재하는지를 자주 체크한다면

list보다는 set을 사용하자.

list는 O(n), set은 O(1)(open hashing 방식이므로)

 

 

 

메모리에 크게 들고 있지 않아도 된다면, generator를 쓸 생각을 하자.

이는 단순히 메모리 절약차원 뿐 아니라, 실제 속도도 더 높을 수가 있다.

순차적으로 sequence내 원소를 합하는 경우, 

단순 큰 list였다면 메모리에 builing하느라 시간을 잡아먹기때문

 

 

 

Global variable을 Local ones로 바꿀 수 있다면 바꿔라

이는 variable search 순서에서 오는 속도높이는 방법인데

local에서 variable을 search할 때, 

local->global->built-in namespace 순서로 찾기 때문이다.

 

 

 

Class property(예를 들면 self._value)를 자주 access한다면

마찬가지로 local variable(class내의 function에서 자주 접근한다면)로 바꿔라.

 

 

 

.function을 자주 쓸 것이면, function을 assign해서 쓰자.

즉, list.append()을 자주 쓸 것이면

appender = list.append라 두고 appender를 쓰자.

이는, function call할 때면 __getattribute__()나 __getattr__()을 호출하게되는데 이 time cost를 줄일 수 있다.

 

 

 

많은 string을 여러번 +연산을 할 때에는 join을 사용하자.

'a' + 'b'을 한다고하면 memory space 요청을 1번 하게 되고 그 때 a와 b를 copy하여 박는다.

'a' + 'b' + 'c'는 memory space요청을 2번하게 된다.

따라서 n개의 string을 +하면 n-1개의 요청을 하게된다.

이 때, join을 쓰면, 전체 필요 memory space를 계산하여 1번만 메모리 요청을 한다.

 

 

 

Multiple conditions에서 condition의 위치는

-if Condition1 and Condition2 에는 1과 2중 False가 자주 뜰 것을 Condition1에 할당

-if Condition1 or Condition2에는 1과 2중 True가 자주 뜰 것을 Condition1에 할당

(short-circuit evaluation, AND 혹은 OR 연산에 있어서 First condition에 의하여 return이 확정되면, 이후 condition은 연산을 실행조차 하지 않는 것을 가리킴)

 

 

 

While문보다는 Foor문을 쓰자.

이는 While문에서 i

 

 

참고자료:

towardsdatascience.com/10-techniques-to-speed-up-python-runtime-95e213e925dc

 

10 Techniques to Speed Up Python Runtime

Compare good writing style and bad writing style with the code runtime

towardsdatascience.com

 

 

728x90

+ Recent posts