Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- Created on Sun Jul 26 09:14:28 2017
- @author: martin
- """
- from random import random
- from random import choice
- from string import ascii_lowercase
- import timeit
- import matplotlib.pyplot as plt
- from collections import OrderedDict
- from strgen import StringGenerator as SG
- # Compared functions
- def scramble(s1, s2):
- return not any(s1.count(char) < s2.count(char) for char in set(s2))
- def scramblef(s1, s2):
- h = [0] * 26
- for c in s1:
- h[ord(c) - 97] += 1
- for c in s2:
- h[ord(c) - 97] -= 1
- return 0 == sum(n < 0 for n in h)
- def string_pair_generator(maximum = 1000):
- """
- Some typical use-case, generates a pair of strings,
- the first string 1/10 the length of the second. Last element of the returned
- tuple is the length of the second string.
- """
- for i in range(1, maximum, 100):
- print("Progress {} / {}, t = {}".format(i, maximum, timeit.default_timer()))
- for j in range(10, maximum // 10, 10):
- s1 = SG("[a-z]{{{}}}".format(i))
- s2 = SG("[a-z]{{{}}}".format(j))
- for k in range(1000): # more result of the same length
- yield (s1.render(), s2.render(), i) # string pair
- def performance_test(test_input, UUT1, UUT2):
- results = OrderedDict() # ordered dict of tuples length -> ( t1, t2)
- for pair in test_input:
- t1 = timeit.default_timer()
- UUT1(pair[0], pair[1])
- dt1 = timeit.default_timer() - t1
- t2 = timeit.default_timer()
- UUT2(pair[0], pair[1])
- dt2 = timeit.default_timer() - t2
- # Add to results
- tmp = results.get(pair[2], (0, 0))
- results[pair[2]] = (tmp[0] + dt1, tmp[1] + dt2)
- return results
- tst_time = timeit.default_timer()
- test_results = performance_test(string_pair_generator(), scramble, scramblef)
- print("Testing took {}s.".format(timeit.default_timer() - tst_time))
- times1 = list()
- times2 = list()
- lengths = list()
- for key, val in test_results.items():
- times1.append(val[0])
- times2.append(val[1])
- lengths.append(key)
- plt.plot(lengths, times1)
- plt.plot(lengths, times2)
- plt.legend(['scramble', 'scramblef'], loc = 'upper left')
- plt.xlabel('Input length [1]')
- plt.ylabel('Time [s]')
- plt.title('Time of computation dependend on input length')
- plt.grid(True)
- plt.savefig("scramble_test.png")
- plt.show()
Advertisement
Add Comment
Please, Sign In to add comment