-
Notifications
You must be signed in to change notification settings - Fork 46
Karpov 7.3, 9.1, 9.2 #295
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
cool07
wants to merge
1
commit into
master
Choose a base branch
from
cool07-patch-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
Karpov 7.3, 9.1, 9.2 #295
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,34 @@ | ||
| import time | ||
| import threading | ||
|
|
||
|
|
||
| def find_primes(start, end): | ||
| primes = [] | ||
| start_time = time.time() | ||
| for i in range(start, end + 1): | ||
| if i > 1: | ||
| for n in range(2, i): | ||
| if (i % n) == 0: | ||
| break | ||
| else: | ||
| primes.append(i) | ||
| print(f"Диапазон от {start} до {end}, время обработки {time.time() - start_time} сек.") | ||
| return primes | ||
|
|
||
| begin = [3, 10001, 20001] | ||
| finish = [10000, 20000, 30000] | ||
|
|
||
| start_seq = time.time() | ||
| for i in range(3): | ||
| find_primes(begin[i], finish[i]) | ||
| print(f"Общее время: {time.time() - start_seq} сек.") | ||
|
|
||
| start_thr = time.time() | ||
| threads = [] | ||
| for i in range(3): | ||
| thread = threading.Thread(target=find_primes, args=(begin[i], finish[i])) | ||
| threads.append(thread) | ||
| thread.start() | ||
| for thr in threads: | ||
| thr.join() | ||
| print(f"Многопоцессорность: {time.time() - start_thr}") | ||
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,36 @@ | ||
| from multiprocessing import Process | ||
| import time | ||
|
|
||
| def add(*args): | ||
| start_time = time.time() | ||
| if isinstance(args[0], int) or isinstance(args[0], float): | ||
| back = 0 | ||
| elif isinstance(args[0], list): | ||
| back = list() | ||
| else: | ||
| back = '' | ||
|
|
||
| for elem in args: | ||
| back += elem | ||
|
|
||
| print('Сложение для {}, затрачено {} sec.'.format(type(args[0]), time.time() - start_time)) | ||
| print(back) | ||
|
|
||
| if __name__ == '__main__': | ||
| args = [('aaa', 'bbbb', 'cccc'), | ||
| (1, 2, 3, 4,), | ||
| (1.1, 2.2, 3.3, 4.4,), | ||
| ([1, 2, 3], ['asd', 'rrr'], [10.3, 2.2],)] | ||
|
|
||
| def my_proc(func, args): | ||
| multiprocess = [] | ||
| for arg in args: | ||
| multiprocess.append(Process(target=func, args=arg)) | ||
| for p in multiprocess: | ||
| p.start() | ||
| yield p | ||
|
|
||
| new_list = list(my_proc(add, args)) | ||
|
|
||
| for p in new_list: | ||
| p.join() |
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,37 @@ | ||
| import random | ||
| import pickle | ||
|
|
||
| class Human(): | ||
| def __init__(self, first_name, last_name, age, hair_color, p_of_residence): | ||
| self.first_name = first_name | ||
| self.last_name = last_name | ||
| self.age = age | ||
| self.hair_color = hair_color | ||
| self.p_of_residence = p_of_residence | ||
| def __str__(self): | ||
| return f"Human: first_name={self.first_name}, last_name={self.last_name}, age={self.age}, hair_color={self.hair_color}," \ | ||
| f" p_of_residence={self.p_of_residence}" | ||
|
|
||
| def fun(num): | ||
| f_name = ['Anton', 'Ksenia', 'Serg', 'Pavel', 'Cemen'] | ||
| l_name = ['Abramov', 'Kitov', 'Block', 'Kazakov', 'Ivanov'] | ||
| p_of_r = ['Moscow', 'Nizhny Novgorod', 'Vladimir', 'St. Petersburg', 'Kazan'] | ||
| hair_color = ['Green', 'Red', 'Blue', 'Gray', 'Black'] | ||
| people = [] | ||
| for i in range(num): | ||
| people.append(Human(random.choice(f_name), random.choice(l_name), random.randint(1, 115), random.choice(hair_color), random.choice(p_of_r))) | ||
| for i in people: | ||
| print(i) | ||
| with open('data.pickle', 'wb') as f: | ||
| pickle.dump(people, f) | ||
| return people | ||
|
|
||
| def fun1(file): | ||
| with open(file, 'rb') as f: | ||
| data_new = pickle.load(f) | ||
| for line in data_new: | ||
| print(line) | ||
| return data_new | ||
|
|
||
| fun(5) | ||
| fun1('data.pickle') |
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.
А где многопроцессность?
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.
if name == 'main':
start_pro = time.time()
processes = []
for i in range(3):
pro = multiprocessing.Process(target=find_primes, args=(begin[i], finish[i]))
processes.append(pro)
pro.start()
for p in processes:
p.join()
print(f"Многопроцессорность: {time.time() - start_pro} сек.")
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.
Добавил. Невнимательно вчитался в задание.
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.
Все-таки было бы интересно посмотреть на код мультипроцессинга вписанный в t9_1.py, т.к. там есть важные нюансы. Также нужен аргументированный вывод, какой из способов решения данной задачи лучше и почему?
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.
В моем примере время обработки информации, с помощью распараллеливания потоков (3.99), оказалось меньше, чем при последовательном выполнении (4.40) и при многопроцессорности (4.64).
Uh oh!
There was an error while loading. Please reload this page.
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.
Вот мне потому и интересно посмотреть, как ваш код в файле выглядит. Т.к. если вы допишете код с процессами в тот же файл даже под прикрытием if __name__ == "main", код, лежащий вне этого условия (я имею в виду код с потоками и последовательное выполнение), выполнится и в дочерних процессах тем самым увеличивая время работы процессов и приводя вас к сомнительному выводу.