def animate(images, *args, **kwargs): if "speed" in kwargs: s = kwargs["speed"] else: s = 100 if "duration" in kwargs: duration = kwargs["duration"] else: duration = 10 if "loop" in args: start = t() f = 0 total = len(images) while t() - start < duration: cv2.imshow(None, images[f]) cv2.waitKey(s) f = (f + 1) % total cv2.waitKey(0) cv2.destroyAllWindows() else: for i in images: cv2.imshow(None, i) cv2.waitKey(s) cv2.waitKey(0) cv2.destroyAllWindows()
def func_wrapper(self, slave_address, *args, **kwargs): request = bytes([slave_address, self.code]) # slave address fun_request_part, num_of_bytes_to_read = func(self, slave_address, *args) # function specific part of request request += fun_request_part request += self._calculate_crc(request) sleep_time = t() - self.modbus.sleep_timer if sleep_time < self.modbus.t_3_5: # if there wasn't enaugh silent time, sleep! time.sleep(sleep_time) self.modbus.serial.write(request) response = self.modbus.serial.read(num_of_bytes_to_read) self.modbus.sleep_timer = t() try: self._validate_response(slave_address, response) except ValueError as e: self.modbus.logger.warn(e) self.modbus.corrupted_frames += 1 self.modbus.consecutive_corrupted_frames += 1 return False else: self.modbus.correct_frames += 1 if self.code in self.READ_FUNCTIONS_CODES: return self._byte_string_to_list(response[self.payload_position : -self.NUMBER_OF_CRC_BYTES]) # return payload return True #return ack
def run(self, func_obj, slave_address, *modbus_fun_args): """ Wrapper for run functions of modbus functions. It expect function's request part and number of bytes to read . "It embedes function request with slave address, fun code, crc. Then it performs write and read, validates response and return either payload or ack, nack. """ request, num_of_bytes_to_read = func_obj.run(slave_address, *modbus_fun_args) # sleep_time = t() - self.sleep_timer if sleep_time < self.t_3_5: # if there wasn't enaugh silent time, sleep! time.sleep(sleep_time) self.serial_port.write(request) response = self.serial_port.read(num_of_bytes_to_read) self.sleep_timer = t() try: func_obj.validate(slave_address, response) except ValueError as e: self.logger.warn(e) self.corrupted_frames += 1 self.consecutive_corrupted_frames += 1 return False else: self.correct_frames += 1 if func_obj.code in ModbusFunction.READ_FUNCTIONS_CODES: # return payload return func_obj.get_payload(response) return True # return ack
def loops_per_second(self, ): self.counter += 1 if t() - self.lps_timer >= 1: self.lps_timer = t() lps = self.counter self.counter = 0 #print('Loops per second: {} '.format(lps)) self.logger.debug('Loops per second: {} '.format(lps)) return True else: return False
def loops_per_second(self,): self.counter += 1 if t() - self.lps_timer >= 1: self.lps_timer = t() lps = self.counter self.counter = 0 #print('Loops per second: {} '.format(lps)) self.logger.debug('Loops per second: {} '.format(lps)) return True else: return False
def main(): start = t() permutations = [] digits = [0,1,2,3,4,5,6,7,8,9] i = 0 for x in permute(digits): i += 1 if i == 1000000: print x break stop = t() print stop - start
def main(): start = t() numbers = set() abundant_n = [] for i in range(1,28123): if find_sum_of_factors(i) > i: abundant_n.append(i) for j in abundant_n: if i + j >= 28123: break numbers.add(i + j) print sum(range(28123))-sum(numbers) stop = t() print stop - start
def fit(self, X, y): if isinstance(self.b, bool): X = np.hstack([np.ones([X.shape[0], 1]), X]) n_samp, n_feat = X.shape self.w = np.random.rand(n_feat) start = t() for _ in range(self.n_iters): z = np.dot(X, self.w) y_pred = self._sigmoid(z) dw = (1 / n_samp) * np.dot(X.T, (y_pred - y)) self.w -= self.lr * dw end = t() print(f'Elapsed time: {end - start:.4f}')
def perf_lap(msg=None): global perf_time_start if msg is not None: msg += " " else: msg = "" end = t() msg += str((end - perf_time_start)) perf_time_start = end print(msg)
def main(args=None): args = ' '.join(sys.argv[1:]) files = [] if len(sys.argv) < 2: args = os.getcwd() if os.path.isdir(args) and os.path.exists(args): files = glob.glob(os.path.join(args, '*.hbr')) if len(files) < 1: sys.exit('No .hbr files found in {}.'.format(args)) if os.path.isfile(args) and os.path.exists(args): files = [args] if len(files) < 1: sys.exit('File {} does not exist.'.format(args)) dirn = os.path.dirname(files[0]) dirn = os.path.join(dirn, 'hbrdumps') if not os.path.exists(dirn): os.makedirs(dirn) print('Dumped file(s) will be saved in the directory "{}"'.format(dirn)) suc, fail, tottime = 0, 0, t() for file in files: basen, ext = os.path.basename(file).split('.') hbrdump = os.path.join(dirn, basen+'.txt') try: start = t() dumped = dump(file) except ParserError as e: print('"{}" -> ERROR: {}'.format(basen, e.reason)) fail+=1 else: print('"{}" -> SUCCESS: dumped to hbrdumps/{}.txt ({}ms)'.format(basen, basen, int((t()-start)*1000))) with open(hbrdump, 'w+') as f: f.write(dumped.prettify()) suc+=1 tottime = int((t()-tottime)*1000) print("\nSUCCESSFUL DUMPS: {}\nFAILED DUMPS: {}\n{}ms ({}ms/hbr)".format(suc, fail, tottime, int(tottime/suc) if suc > 0 else 0))
def start(self, ): t()
self.modbus.open_serial() self.modbus.consecutive_corrupted_frames = 0 self.logger.warn("Serial reload") #is_second_passed = bench.loops_per_second() #if is_second_passed: # self.modbus.debug() else: self.logger.error('Modbus connection error. Thread {} exits'.format(self.name)) if __name__ == "__main__": import queue from timeit import default_timer as t from backend.misc.color_logs import color_logs from backend.objects_loader import objects_loader start = t() color_logs() objects_loader() tasks = queue.Queue() modbus_manager = Modbus_manager(args=(tasks,)) modbus_manager.logger.disabled = False modbus_manager.logger.setLevel("DEBUG") print("Set up took: {0:.2f} miliseconds".format((t()-start)*1000)) while True: modbus_manager.run()
def loop_time(): global lt_timer lt = t() - lt_timer lt_timer = t() return lt
def main(): start = t() ## print eratosthenes_sieve(10000) rwh_primes1(2001000) stop = t() print('done - took: ' + str(stop - start))
def before_request(): g.start = t()
def loop_time(self): lt = t() - self.lt_timer self.lt_timer = t() return lt
def perf_start(): global perf_time_start perf_time_start = t()
def start_timing_snippet(self, ): self.snipet_timer = t()
def get_snippet_time(self, ): return t()-self.snipet_timer
def binominal_item_test(nkab): n, k, a, b = nkab sum = 0 for k in range(n+1): arg=n,k,a,b print type(arg), arg coefficient,a,a_factor,b,b_factor = binominal_item(arg) sum += coefficient * a**a_factor * b**b_factor print "test:{}, ref:{}".format(sum, (a+b)**n) #main def _main(*argv): pass if __name__ == "__main__": #sys.exit(_main(*sys.argv)) from timeit import timeit as t from guppy import hpy h= hpy() f1=factorial f2=factorial2 print t("f1(100)", setup ="from __main__ import f1", number = 10000) print t("f2(100)", setup ="from __main__ import f2", number = 10000) print h.iso(f1) print h.iso(f2) print h.heap() print h.heap().more print h.heap().more #with open("temp.txt","r+") as doc: # doc.write(str(h.heap()))
def test(): x = 0 x = x+1 def test2(): x = 0 x += 1 # List comprehension test def test3(): res = [w for w in ws if w in hs] # Generator test def test4(): # This determines number of elements in generator object # but is no faster than list comprehension in test3() # sum(1 for i in (w for w in ws if w in hs)) res = (w for w in ws if w in hs) if __name__ == '__main__': # print(t("test", setup="from __main__ import test", number=1000000)) # print(t("test2()", setup="from __main__ import test2", number=1000000)) # Result ~14.4706 sec print(t("test3()", setup="from __main__ import test3", number=100000)) # Result ~0.02156 sec print(t("test4()", setup="from __main__ import test4", number=100000))
from timeit import timeit as t from math import factorial def fact(n): f = 1 for i in range(1,n,2): f *= i**2 + i return f if not n%2 else f*n def fact2(n): f=1 for i in range(1,n+1): f*=i return f number = 10000 assert fact(number) == fact2(number)== factorial(number) print("Moje:{}".format(t("fact(10000)","from __main__ import fact", number=100))) print("Moj2e:{}".format(t("fact2(10000)","from __main__ import fact2", number=100))) print("Stand:{}".format(t("factorial(10000)","from math import factorial", number=100)))
print(model.summary()) print() print() print('*****************************************************************') print() print() print('1 Epoch') print() # CPU with tf.device('/CPU:0'): print('CPU') model_cpu = get_model() t1 = t() model_cpu.fit(X_train_scaled, y_train_encoded, epochs=1) t2 = t() T = t2 - t1 print('Time of training: {:.2f} s'.format(T)) print() # GPU if tf.test.is_built_with_cuda(): with tf.device('/GPU:0'): print('GPU') model_gpu = get_model() t1 = t() model_gpu.fit(X_train_scaled, y_train_encoded, epochs=1) t2 = t() T = t2 - t1
def get_snippet_time(self, ): return t() - self.snipet_timer
def start(self,): t()
""" # -*- coding: utf-8 -*- """ Created on Fri Dec 20 17:31:45 2019 @author: a7md_ """ """ 1- to call the packages form python library """ import matplotlib.pyplot # for graphics from agentframework import Agent # for call agentframework file from matplotlib.animation import FuncAnimation # to be able to create an animation graphics by import it from timeit import default_timer as t # the codes from this line to line 23 from this website: https://stackoverflow.com/questions/7370801/measure-time-elapsed-in-python : start = t() # this code have been used to timed the cods end = t() print(end - start) """ 2- Create lists for every variable we need to built the project """ agents = [] # this list is represent the Drunks. environment = [] # this list represent the map. houses = {num:[]for num in range(10,260,10)} # this dictionary which have key for every house and that represent the drunks houses ever, and drunker have a specific house in the map. in_home_agents= [] # every agent reach his house will be add in this list. fig = matplotlib.pyplot.figure() carry_on = True # to activate """ 3- Locate the Pub and Houses, and that can be work if we built the list and defend the value 1 is the pub by writing the next function and the values between 10 to 260 mark it as house for every value """
'''Average runtime 7.39 seconds on my computer''' import numpy as np from timeit import default_timer as t def prepare_data(): np.random.RandomState(100) arr = np.random.randint(0, 10, size=[300000, 150]) return arr.tolist() def find_nums_within_range_for_current_row(row, minimum, maximum): """Returns how many numbers lie within `maximum` and `minimum` in a given `row`""" count = 0 for n in row: if minimum <= n <= maximum: count = count + 1 return count if __name__ == "__main__": data = prepare_data() start = t() for row in data: find_nums_within_range_for_current_row(row, minimum=4, maximum=8) elapsed_time = t() - start print(f'Elapsed time: {elapsed_time:.2f} seconds')
# return chr(msb) + chr(lsb) #def _two_byte_str_to_num(byte_string): # value = ord(byte_string[0])*256 + ord(byte_string[1]) # return value from timeit import default_timer as t from time import sleep min = 1 max = 0 num_of_empty_loops = 1700 for j in range (1000): start = t() while t()-start < 9e-05: pass dur = t()-start if dur < min: min = dur if dur > max: max = dur min = min * 1000000 max = max * 1000000 print ('min: {}, max: {}'.format(min, max))
def after_request(response): diff = t() - g.start print(request.path + ': ' + str(diff) + 's') return response
# it's a globalized world kv_latest = [] lines = [] x = r.urlopen('http://feeds.kexp.org/kexp/musicthatmatters', data=None, timeout=5) # jawn # good jawn? if x.getcode() != 200: print("[!] Warning [!]") else: print("successfully accessed website") # new jawn? try: t_tb1_s = t() dump = BeautifulSoup(x, 'lxml-xml') if len(dump) > 0: a = dump.find_all("description") new = str(a[1].get_text()) else: print("dump failed") except Exception as e: print(e.message) # TRY BLOCK TWO: let's create a csv(?) containing the songs aired on the latest podcast try: lines = re.split("\s\d+.\s", new) cnt = 1 song_list = [] # make a jawn
""" from timeit import timeit as t def first_word(text): index = text.find(" ") return text[:index] if index != -1 else text def first_word_1(text): return text.split(" ")[0] print( t('first_word_1(x)', setup='x = "asdf we"*10', number=10000, globals=globals())) # ~11.7 ms print( t('first_word_1(x)', setup='x = "asdfawe"*10', number=10000, globals=globals())) # ~6.1 ms print( t('first_word_1(x)', setup='x = "asdf we"*100000', number=10000, globals=globals())) # ~90928.2 ms print( t('first_word_1(x)', setup='x = "asdfawe"*100000', number=10000,
1, 2, 4, 6, 7, 9, 10, 10, 10, 11, 12, 12, 15, 20, 20, 20, 20, 20, 25, 30 ] print(f"{VALUES = }") @lru_cache def find_optimal_cuts(length: int) -> Result: # assume we make no cuts best_result = Result(VALUES[length - 1], [length]) for i in range(1, length // 2 + 1): left_result = find_optimal_cuts(i) right_result = find_optimal_cuts(length - i) # check if this is a better result if best_result.value < (best_value := (left_result.value + right_result.value)): best_result.update(best_value, left_result.cuts + right_result.cuts) return best_result if __name__ == "__main__": for length in range(1, LENGTH + 1): t0 = t() result = find_optimal_cuts(length) t1 = t() print(f"The best value for {length} rod cuts are: {result}.") print(f"Calc time {t1 - t0:.6f} secs")
else: a[i] = np.ceil(a[i]) elif (a.ndim == 2): #for 2D array for i in range(array.shape[0]): for j in range(array.shape[1]): if ((f[i, j] < 0.0 and f[i, j] <= -0.5) or (f[i, j] >= 0.0 and f[i, j] < 0.5)): a[i, j] = np.floor(a[i, j]) else: a[i, j] = np.ceil(a[i, j]) elif (a.ndim == 3): #for 3D array for i in range(array.shape[0]): for j in range(array.shape[1]): for k in range(array.shape[2]): if ((f[i, j, k] < 0.0 and f[i, j, k] <= -0.5) or (f[i, j, k] >= 0.0 and f[i, j, k] < 0.5)): a[i, j, k] = np.floor(a[i, j, k]) else: a[i, j, k] = np.ceil(a[i, j, k]) return a upset = '''from pfb_floating_numba import FloatPFB import numpy as np data = np.ones(8*2**13) pfbflt = FloatPFB(2**13,8, chan_acc = True)''' code = '''pfbflt.run(data)''' print(t(stmt=code, setup=upset, number=1000))