Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Practice/Karpov_A/Lec9/t9_1.py
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}")
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А где многопроцессность?

Copy link
Copy Markdown
Collaborator Author

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} сек.")

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Добавил. Невнимательно вчитался в задание.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Все-таки было бы интересно посмотреть на код мультипроцессинга вписанный в t9_1.py, т.к. там есть важные нюансы. Также нужен аргументированный вывод, какой из способов решения данной задачи лучше и почему?

Copy link
Copy Markdown
Collaborator Author

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).

Copy link
Copy Markdown
Owner

@IlyaOrlov IlyaOrlov Sep 24, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот мне потому и интересно посмотреть, как ваш код в файле выглядит. Т.к. если вы допишете код с процессами в тот же файл даже под прикрытием if __name__ == "main", код, лежащий вне этого условия (я имею в виду код с потоками и последовательное выполнение), выполнится и в дочерних процессах тем самым увеличивая время работы процессов и приводя вас к сомнительному выводу.

36 changes: 36 additions & 0 deletions Practice/Karpov_A/Lec9/t9_2.py
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()
37 changes: 37 additions & 0 deletions Practice/Karpov_A/t7_3.py
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')