Skip to content

Instantly share code, notes, and snippets.

@polymorphm
Created February 9, 2014 18:18
Show Gist options
  • Save polymorphm/8903485 to your computer and use it in GitHub Desktop.
Save polymorphm/8903485 to your computer and use it in GitHub Desktop.
script for testing how much cost of creating thread
#!/usr/bin/env python3
# -*- mode: python; coding: utf-8 -*-
import datetime
import threading
def test(n, use_thread=None):
if use_thread is None:
use_thread = True
for x in range(n):
stop_event = threading.Event()
func_result = {}
def func(x):
y = (2 ** (x * 10) % 1000)
func_result['y'] = y
in_func_delta = datetime.datetime.now() - begin_time
print('*** x:{!r} y:{!r} use_thread:{!r} in_func_delta:{!r}***'.format(
x, y, use_thread, in_func_delta))
stop_event.set()
begin_time = datetime.datetime.now()
if use_thread:
thr = threading.Thread(target=func, args=(x,))
thr.start()
else:
func(x)
stop_event.wait()
event_delta = datetime.datetime.now() - begin_time
if use_thread:
thr.join()
join_delta = datetime.datetime.now() - begin_time
print('*** x:{!r} y:{!r} use_thread:{!r} event_delta:{!r} ***'.format(
x, func_result['y'], use_thread, event_delta))
print('*** x:{!r} y:{!r} use_thread:{!r} join_delta:{!r} ***'.format(
x, func_result['y'], use_thread, join_delta))
print('--')
if __name__ == '__main__':
test(10, use_thread=True)
test(10, use_thread=False)
test(10, use_thread=True)
test(10, use_thread=False)
legend_seconds = 0.9
print('hint: {!r} seconds is {!r}'.format(
legend_seconds, datetime.timedelta(seconds=legend_seconds)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment