-
Notifications
You must be signed in to change notification settings - Fork 77
Lesson_6 #602
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kalenikai
wants to merge
1
commit into
DmitryChitalov:master
Choose a base branch
from
kalenikai:Lesson_6
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Lesson_6 #602
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| """ | ||
| Задание 1. | ||
|
|
||
| Выполните профилирование памяти в скриптах | ||
| Проанализировать результат и определить программы с | ||
| наиболее эффективным использованием памяти. | ||
|
|
||
| Примечание: Для анализа возьмите любые 1-5 ваших разных скриптов!. | ||
| Сделать их разные реализации. | ||
|
|
||
| Можно взять задачи с курса Основ | ||
| или с текущего курса Алгоритмов | ||
|
|
||
| Результаты анализа вставьте в виде комментариев к коду. | ||
| Также укажите в комментариях версию Python и разрядность вашей ОС. | ||
|
|
||
| ВНИМАНИЕ: ЗАДАНИЯ, В КОТОРЫХ БУДУТ ГОЛЫЕ ЦИФРЫ ЗАМЕРОВ (БЕЗ АНАЛИТИКИ) | ||
| БУДУТ ПРИНИМАТЬСЯ С ОЦЕНКОЙ УДОВЛЕТВОРИТЕЛЬНО | ||
|
|
||
| Попытайтесь дополнительно свой декоратор используя ф-цию memory_usage из memory_profiler | ||
| С одновременным замером времени (timeit.default_timer())! | ||
| """ | ||
| import memory_profiler | ||
| import time | ||
|
|
||
| # | ||
| def get_odd_1(value): | ||
| result = [] | ||
| for var in range(value): | ||
| if var % 2: | ||
| result.append(var) | ||
|
|
||
| def get_odd_2(value): | ||
| return [var for var in range(value) if var % 2] | ||
|
|
||
| def get_odd_3(value): | ||
| for num in range(value): | ||
| if num % 2: | ||
| yield num | ||
|
|
||
| if __name__ == '__main__': | ||
| value = 10000000 | ||
| t1 = time.process_time() | ||
| m1 = memory_profiler.memory_usage() | ||
| get_odd_1(value) | ||
| t2 = time.process_time() | ||
| m2 = memory_profiler.memory_usage() | ||
| print(f"Выполнение get_odd_1 заняло {t2 - t1} сек and {m2[0] - m1[0]} Мб") | ||
|
|
||
| t1 = time.process_time() | ||
| m1 = memory_profiler.memory_usage() | ||
| get_odd_2(value) | ||
| t2 = time.process_time() | ||
| m2 = memory_profiler.memory_usage() | ||
| print(f"Выполнение get_odd_2 заняло {t2 - t1} сек and {m2[0] - m1[0]} Мб") | ||
|
|
||
| t1 = time.process_time() | ||
| m1 = memory_profiler.memory_usage() | ||
| mygenerator = get_odd_3(value) | ||
| for i in mygenerator: | ||
| i | ||
| t2 = time.process_time() | ||
| m2 = memory_profiler.memory_usage() | ||
| print(f"Выполнение get_odd_3 и цикла заняло {t2 - t1} сек and {m2[0] - m1[0]} Мб") | ||
|
|
||
| """ | ||
| Выполнение get_odd_1 заняло 0.078125 сек and 1.33203125 Мб | ||
| Выполнение get_odd_2 заняло 0.046875 сек and 0.00390625 Мб | ||
| Выполнение get_odd_1 и цикла заняло 0.0625 сек and 0.0 Мб | ||
| С точки зренеия оптимальности времени выполнения генераторное выражение оптимально, однако с точки зрения использования памяти generator - имеет неоспоримые преимущества. | ||
| Как я понимаю генераторная (generator) функция выполняется долго из-за цикла, в котором получаются выходные значения. | ||
| Python 3.8.4 (tags/v3.8.4:dfa645a, Jul 13 2020, 16:46:45) [MSC v.1924 64 bit (AMD64)] | ||
| """ | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| """ | ||
| Задание 2.* | ||
| Предложить еще какие-либо варианты (механизмы, библиотеки) для оптимизации памяти и | ||
| доказать! (наглядно, кодом) их эффективность (на примере профилировщика) | ||
| """ | ||
| from functools import total_ordering | ||
| import memory_profiler | ||
| from pympler import asizeof | ||
| from sys import getsizeof | ||
|
|
||
| class Number_1: | ||
| def __init__(self, value): | ||
| self.value = value | ||
|
|
||
| def __eq__(self, other): | ||
| return self.value == other | ||
|
|
||
| def __lt__ (self, other): | ||
| return self.value < other | ||
|
|
||
| def __le__ (self, other): | ||
| return self.value <= other | ||
|
|
||
| def __gt__ (self, other): | ||
| return self.value > other | ||
|
|
||
| def __ge__ (self, other): | ||
| return self.value >= other | ||
|
|
||
| @total_ordering | ||
| class Number_2: | ||
| def __init__(self, value): | ||
| self.value = value | ||
|
|
||
| def __eq__(self, other): | ||
| return self.value == other | ||
|
|
||
| def __lt__ (self, other): | ||
| return self.value < other | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
|
|
||
| m1 = memory_profiler.memory_usage() | ||
| num1 = Number_1(5) | ||
| num2 = Number_1(3) | ||
| print(num1 == num2) | ||
| print(num1 < num2) | ||
| print(num1 <= num2) | ||
| print(num1 > num2) | ||
| print(num1 >= num2) | ||
| m2 = memory_profiler.memory_usage() | ||
| print(f"Работа с Number_1 {m2[0] - m1[0]} Мб") | ||
| print(asizeof.asizeof(Number_1)) | ||
|
|
||
| m1 = memory_profiler.memory_usage() | ||
| num3 = Number_2(5) | ||
| num4 = Number_2(3) | ||
| print(num3 == num4) | ||
| print(num3 < num4) | ||
| print(num3 <= num4) | ||
| print(num3 > num4) | ||
| print(num3 >= num4) | ||
| m2 = memory_profiler.memory_usage() | ||
| print(f"Работа с Number_1 {m2[0] - m1[0]} Мб") | ||
| print(asizeof.asizeof(Number_1)) | ||
|
|
||
| """ | ||
| Должно оптимизировать, но профилировщик показывает нули. | ||
|
|
||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. в чем суть оптимизации |
||
| """ | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| """ | ||
| Задание 3 *. | ||
| Сделать профилировку для скриптов с рекурсией и сделать описание, | ||
| можно ли так профилировать и есть ли 'подводные камни' в профилировании? | ||
| Придумать как это решить! | ||
| Есть очень простое решение! | ||
| """ | ||
| import time | ||
|
|
||
| def time_of_function(function): | ||
| def wrapped(*args): | ||
| start_time = time.perf_counter() | ||
| res = function(*args) | ||
| print(f'Execution time for {function} is {time.perf_counter() - start_time} sec') | ||
| return res | ||
| return wrapped | ||
|
|
||
| @time_of_function | ||
| def reverse_digits(number): | ||
| rev = str(number % 10) | ||
| if number != 0: | ||
| return rev + reverse_digits(number // 10) | ||
| else: | ||
| return '' | ||
|
|
||
|
|
||
| print(reverse_digits(123)) | ||
|
|
||
| """ | ||
| Как решить проблему с многократными вызовами декоратора не нашел. | ||
| """ | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. не выполнено |
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
на уроке мы договорились, что нужно взять хотя бы два скрипта
согласитесь один - слишком мало для закрепления темы