Skip to content

Commit f6004ed

Browse files
committed
fibonacci threaded (3 and 2.7) and non-threaded
0 parents  commit f6004ed

File tree

5 files changed

+464
-0
lines changed

5 files changed

+464
-0
lines changed

.gitignore

Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
*.swp
2+
*.log
3+
.env
4+
# Byte-compiled / optimized / DLL files
5+
__pycache__/
6+
*.py[cod]
7+
*$py.class
8+
9+
# C extensions
10+
*.so
11+
12+
# Distribution / packaging
13+
.Python
14+
build/
15+
develop-eggs/
16+
dist/
17+
downloads/
18+
eggs/
19+
.eggs/
20+
lib/
21+
lib64/
22+
parts/
23+
sdist/
24+
var/
25+
wheels/
26+
share/python-wheels/
27+
*.egg-info/
28+
.installed.cfg
29+
*.egg
30+
MANIFEST
31+
32+
# PyInstaller
33+
# Usually these files are written by a python script from a template
34+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
35+
*.manifest
36+
*.spec
37+
38+
# Installer logs
39+
pip-log.txt
40+
pip-delete-this-directory.txt
41+
42+
# Unit test / coverage reports
43+
htmlcov/
44+
.tox/
45+
.nox/
46+
.coverage
47+
.coverage.*
48+
.cache
49+
nosetests.xml
50+
coverage.xml
51+
*.cover
52+
*.py,cover
53+
.hypothesis/
54+
.pytest_cache/
55+
cover/
56+
57+
# Translations
58+
*.mo
59+
*.pot
60+
61+
# Django stuff:
62+
*.log
63+
local_settings.py
64+
db.sqlite3
65+
db.sqlite3-journal
66+
67+
# Flask stuff:
68+
instance/
69+
.webassets-cache
70+
71+
# Scrapy stuff:
72+
.scrapy
73+
74+
# Sphinx documentation
75+
docs/_build/
76+
77+
# PyBuilder
78+
.pybuilder/
79+
target/
80+
81+
# Jupyter Notebook
82+
.ipynb_checkpoints
83+
84+
# IPython
85+
profile_default/
86+
ipython_config.py
87+
88+
# pyenv
89+
# For a library or package, you might want to ignore these files since the code is
90+
# intended to run in multiple environments; otherwise, check them in:
91+
# .python-version
92+
93+
# pipenv
94+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
95+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
96+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
97+
# install all needed dependencies.
98+
#Pipfile.lock
99+
100+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
101+
__pypackages__/
102+
103+
# Celery stuff
104+
celerybeat-schedule
105+
celerybeat.pid
106+
107+
# SageMath parsed files
108+
*.sage.py
109+
110+
# Environments
111+
.env
112+
.venv
113+
env/
114+
venv/
115+
ENV/
116+
env.bak/
117+
venv.bak/
118+
119+
# Spyder project settings
120+
.spyderproject
121+
.spyproject
122+
123+
# Rope project settings
124+
.ropeproject
125+
126+
# mkdocs documentation
127+
/site
128+
129+
# mypy
130+
.mypy_cache/
131+
.dmypy.json
132+
dmypy.json
133+
134+
# Pyre type checker
135+
.pyre/
136+
137+
# pytype static type analyzer
138+
.pytype/
139+
140+
# Cython debug symbols
141+
cython_debug/

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Python Threading Examples
2+
3+
This Python threading example is a script I whipped up to showcase how threading works. It will go hand in hand with a write up I posted on Medium.
4+
5+
To check how the file works, simply run the file with the `--help` flag.
6+
7+
There are two versions of the example (python2.7 and python3) since the switch to python3 happened only this past January. While there are next to no code changes, I wanted to demonstrate how using my helper function `log` to encapsulate `print` calls allowed me to copy-paste the script from 3 to 2.7 and change 2 lines of code instead of every single print statement in the document. Also note, the program creates a `*.log` file for all your viewing pleasure.
8+
9+
> Created by Spencer Pollock (@srepollock)

fibonacci.py

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
#!/usr/bin/env python3
2+
import argparse
3+
import logging
4+
import time
5+
import threading
6+
import random
7+
8+
'''
9+
Global Variables
10+
'''
11+
DEBUG = False
12+
VERBOSE = False
13+
14+
MESSAGE_TYPE = {
15+
'debug': 'debug',
16+
'info': 'info',
17+
'warning': 'warning',
18+
'critical': 'critical'
19+
}
20+
21+
'''
22+
Classes and Functions
23+
'''
24+
def log(message, message_type=MESSAGE_TYPE['info']):
25+
'''
26+
Logs messages to the user and the logger
27+
'''
28+
global VERBOSE
29+
global DEBUG
30+
global MESSAGE_TYPE
31+
if VERBOSE:
32+
print (message)
33+
elif DEBUG or message_type == MESSAGE_TYPE['debug']:
34+
print (message)
35+
logging.debug(message)
36+
elif message_type == MESSAGE_TYPE['info']:
37+
logging.info(message)
38+
elif message_type == MESSAGE_TYPE['warning']:
39+
logging.warning(message)
40+
elif message_type == MESSAGE_TYPE['critical']:
41+
logging.critical(message)
42+
return
43+
44+
45+
def fibonacci(function_id, max_index=10):
46+
data = [0 for x in range(max_index)]
47+
data[0] = 1
48+
data[1] = 1
49+
i = 0
50+
j = 1
51+
for value in range(2, max_index):
52+
log('Fibonacci function {} calculating...'.format(function_id))
53+
data[value] = data[i] + data[j]
54+
i += 1
55+
j += 1
56+
log('Fibonacci {} is done it\'s sequence of {} fibonacci numbers\n{}'.format(function_id, max_index, data))
57+
return
58+
59+
'''
60+
Main runner
61+
'''
62+
def get_args():
63+
'''
64+
Gets the arguments for the user
65+
66+
Returns the arguments from the user in a Key,Value Namespace.
67+
'''
68+
description = '''
69+
Python Threading Tutorial
70+
71+
Please see the README for more details.
72+
73+
Created by Spencer Pollock (spencer@spollock.ca)
74+
'''
75+
parser = argparse.ArgumentParser(description=description)
76+
parser.add_argument('-n', '--number-of-runs', dest='numberofruns', type=int, default=2, help='Number of times to run the fibonacci sequence')
77+
78+
parser.add_argument('--verbose', action='store_true', help='Run the program in verbose mode')
79+
parser.add_argument('--debug', action='store_true', help='Run the program in debug mode')
80+
return parser.parse_args()
81+
82+
def main(args):
83+
global DEBUG
84+
global VERBOSE
85+
global MESSAGE_TYPE
86+
DEBUG = args.debug
87+
VERBOSE = args.verbose
88+
if (DEBUG):
89+
log('Debug mode is {}'.format(DEBUG), MESSAGE_TYPE['info'])
90+
if (VERBOSE):
91+
log('Verbose mode is {}'.format(VERBOSE), MESSAGE_TYPE['info'])
92+
start_time = time.time()
93+
for i in range(0, args.numberofruns):
94+
fibonacci(i, random.randint(1500,2000))
95+
log('All fibonacci functions complete', MESSAGE_TYPE['info'])
96+
log('Took {} time to run {} Fibonacci functions'.format(time.time() - start_time, args.numberofruns))
97+
return 0
98+
99+
if __name__ == "__main__":
100+
logging.basicConfig(format='%(asctime)s = %(message)s', filename='fibonacci.log', level=logging.DEBUG, datefmt='%Y-%m-%d %H:%M:%S')
101+
main(get_args())
102+
logging.shutdown()

pythread27.py

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
#!/usr/bin/env python2.7
2+
import argparse
3+
import logging
4+
import time
5+
import threading
6+
import random
7+
8+
'''
9+
Global Variables
10+
'''
11+
DEBUG = False
12+
VERBOSE = False
13+
14+
MESSAGE_TYPE = {
15+
'debug': 'debug',
16+
'info': 'info',
17+
'warning': 'warning',
18+
'critical': 'critical'
19+
}
20+
21+
'''
22+
Classes and Functions
23+
'''
24+
def log(message, message_type=MESSAGE_TYPE['info']):
25+
'''
26+
Logs messages to the user and the logger
27+
'''
28+
global VERBOSE
29+
global DEBUG
30+
global MESSAGE_TYPE
31+
if VERBOSE:
32+
print message
33+
elif DEBUG or message_type == MESSAGE_TYPE['debug']:
34+
print message
35+
logging.debug(message)
36+
elif message_type == MESSAGE_TYPE['info']:
37+
logging.info(message)
38+
elif message_type == MESSAGE_TYPE['warning']:
39+
logging.warning(message)
40+
elif message_type == MESSAGE_TYPE['critical']:
41+
logging.critical(message)
42+
return
43+
44+
def fibonacci(thread_id, max_index=10):
45+
data = [0 for x in range(max_index)]
46+
data[0] = 1
47+
data[1] = 1
48+
i = 0
49+
j = 1
50+
for value in range(2, max_index):
51+
log('Thread {} calculating...'.format(thread_id))
52+
data[value] = data[i] + data[j]
53+
i += 1
54+
j += 1
55+
log('Thread {} is done it\'s sequence of {} fibonacci numbers\n{}'.format(thread_id, max_index, data))
56+
return
57+
58+
'''
59+
Main runner
60+
'''
61+
def get_args():
62+
'''
63+
Gets the arguments for the user
64+
65+
Returns the arguments from the user in a Key,Value Namespace.
66+
'''
67+
description = '''
68+
Python Threading Tutorial
69+
70+
Please see the README for more details.
71+
72+
Created by Spencer Pollock (spencer@spollock.ca)
73+
'''
74+
parser = argparse.ArgumentParser(description=description)
75+
parser.add_argument('-n', '--number-of-threads', dest='numberofthreads', type=int, default=2, help='Number of threads to run in the program')
76+
parser.add_argument('--verbose', action='store_true', help='Run the program in verbose mode')
77+
parser.add_argument('--debug', action='store_true', help='Run the program in debug mode')
78+
return parser.parse_args()
79+
80+
def main(args):
81+
global DEBUG
82+
global VERBOSE
83+
global MESSAGE_TYPE
84+
DEBUG = args.debug
85+
VERBOSE = args.verbose
86+
if (DEBUG):
87+
log('Debug mode is {}'.format(DEBUG), MESSAGE_TYPE['info'])
88+
if (VERBOSE):
89+
log('Verbose mode is {}'.format(VERBOSE), MESSAGE_TYPE['info'])
90+
start_time = time.time()
91+
threads = []
92+
for i in range(0, args.numberofthreads):
93+
log("Starting thread {}".format(i), MESSAGE_TYPE['info'])
94+
t = threading.Thread(name='Thread%d' % i, target=fibonacci, args=(i, random.randint(75,100)))
95+
t.start()
96+
threads.append(t)
97+
for t in threads:
98+
t.join()
99+
log('All threads completed. Exiting', MESSAGE_TYPE['info'])
100+
log('Took {} time to run {} Fibonacci function threads'.format(time.time() - start_time, args.numberofthreads))
101+
return 0
102+
103+
if __name__ == "__main__":
104+
logging.basicConfig(format='%(asctime)s = %(message)s', filename='pythread27.log', level=logging.DEBUG, datefmt='%Y-%m-%d %H:%M:%S')
105+
main(get_args())
106+
logging.shutdown()

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy