-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpycount.py
More file actions
85 lines (73 loc) · 2.45 KB
/
pycount.py
File metadata and controls
85 lines (73 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python3
import multiprocessing
import time
import sys
import os
from datetime import timedelta
def count_up(start, end, result_queue):
count = 0
for i in range(start, end):
count += 1
result_queue.put(count)
def uin_Int():
while True:
os.system('clear')
uin = input("Enter a number or 'q' to quit: ")
try:
if uin == 'q':
os.system('clear')
print("Goodbye!")
time.sleep(2.0)
os.system('clear')
sys.exit(0)
else:
nuin = int(uin)
break
except ValueError:
os.system('clear')
print("Error! You need to enter an integer.")
time.sleep(2.0)
return nuin
def ucpu():
while True:
num_processors = os.cpu_count()
print("Number of CPU cores available: " + str(num_processors))
ucpui = input("Enter the number of cores you would like to use: ")
try:
ucpue = int(ucpui)
if ucpue <= num_processors:
break
else:
os.system('clear')
print("Error! The number you entered exceeds the amount of CPU cores available. Try again.")
time.sleep(2.0)
except ValueError:
os.system('clear')
print("Error! The value entered must be an integer.")
time.sleep(2.0)
return ucpue
def main():
nuin = int(uin_Int())
ucpue = int(ucpu())
print(" Counting to " + format(nuin, ',d')) #Format output to a more readable number
print(" Using total number of CPU cores: " + str(ucpue))
chunk_size = nuin // ucpue
start = 0
result_queue = multiprocessing.Queue()
processes = []
start_time = time.time()
for _ in range(ucpue):
end = start + chunk_size
process = multiprocessing.Process(target=count_up, args=(start, end, result_queue))
processes.append(process)
start = end
for process in processes:
process.start()
for process in processes:
process.join()
total_count = sum(result_queue.get() for _ in range(ucpue))
end_time = time.time()
endtd = timedelta(seconds=(end_time - start_time)) # How long did it take?
print(" Completed in: " + str(endtd)[:-3] + " seconds") #Limit to three decimal points and keep it clean
if __name__ == "__main__":
main()