def compare_LCS(seq1, seq2): """ Computes the longest common subsequence of seq 1 and seq2 in two different ways and compares the execution times of the two approaches. """ timer_std = Stopwatch() # Each function has its own stopwatch timer_memo = Stopwatch() # to keep track of elapsed time independently timer_std.start() # Time the standard LCS function subseq_std = LCS(seq1, seq2) timer_std.stop() timer_memo.start() # Time the memoized LCS function subseq_memo = LCS_memoized(seq1, seq2) timer_memo.stop() # Report results print(seq1) print(seq2) print(subseq_std, len(subseq_std), '(Standard: {:f})'.format(timer_std.elapsed())) print(subseq_memo, len(subseq_memo), '(Memoized: {:f})'.format(timer_memo.elapsed())) print() # Show the computed longest common subsequences highlight(seq1, subseq_std) highlight(seq2, subseq_std) print() highlight(seq1, subseq_memo) highlight(seq2, subseq_memo) return timer_std.elapsed(), timer_memo.elapsed()
async def _ping(self, ctx): stopwatch_banco = Stopwatch() async with self.bot.db_connection.acquire() as conn: await conn.fetch('select version();') stopwatch_banco.stop() e1 = discord.Embed( title=f'Calculando ping {self.bot.emoji("loading")}', colour=discord.Colour.random(), timestamp=datetime.utcnow()) e1.set_footer(text=f'{ctx.author}', icon_url=f'{ctx.author.avatar_url}') stopwatch_message = Stopwatch() mensagem_do_bot = await ctx.reply(embed=e1, mention_author=False) stopwatch_message.stop() e2 = discord.Embed( title= f'🏓 Latência da API: {prettify_number(int(self.bot.latency * 1000))}ms!\n' f'{self.bot.emoji("database")} Tempo de resposta do banco: {stopwatch_banco}!\n' f'📥 Tempo de resposta no discord: {stopwatch_message}!', colour=discord.Colour.random(), timestamp=datetime.utcnow()) e2.set_footer(text=f'{ctx.author}', icon_url=f'{ctx.author.avatar_url}') await asyncio.sleep(stopwatch_message.duration * 2) await mensagem_do_bot.edit( embed=e2, allowed_mentions=discord.AllowedMentions(replied_user=False))
def compute_fitness(representation, chunk): sw = Stopwatch() sw.start() score = 0 gene_ct = 0 covered_pts = set([]) for color in representation.keys(): lab_c1 = to_lab_color(color) sw2 = Stopwatch() sw2.start() for allele in representation[color]: gene_ct += 1 pts = allele.allele_pts() for pt in pts: pt_color = to_lab_color(TARGET_ARRAY[chunk][pt[0], pt[1]]) dist = color_distance(lab_c1, pt_color) # print("pt {} draw {} dist {}".format(color, pt_color, dist)) score += 50 - dist if pt in covered_pts: score -= 1000 covered_pts.add(pt) # print("color {}".format(sw2.reset())) # score -= gene_ct ** 2 score -= (PAPER_WIDTH * PAPER_HEIGHT - len(covered_pts)) #print("fitness in {}".format(sw.reset())) if gene_ct > 0: return score return -1e128
async def _ping(self, ctx): from stopwatch import Stopwatch stopwatch_banco = Stopwatch() conexao = Conexao() stopwatch_banco.stop() conexao.fechar() stopwatch_message = Stopwatch() mensagem_do_bot = await ctx.send(f'Calculando ping...') stopwatch_message.stop() await mensagem_do_bot.edit( content= f'Latência da API do discord: {(self.bot.latency * 1000):.2f}ms!\n' f'Tempo para se conectar ao banco de dados: {str(stopwatch_banco)}!\n' f'Tempo para enviar uma mensagem: {str(stopwatch_message)}!\n' '<a:hello:755774680949850173>')
def run(self): poll_obj = poll() calculate_obj = Calculate() if len(self.names) > 0: for server in self.names: stopwatch = Stopwatch() comm = "openstack server delete " + server stopwatch.start() os.system(comm) SERVER_LIST.append(server) while True: delete_status = poll_obj.delete_server(server) if delete_status == 1: TIME_LIST.append(stopwatch.time_elapsed) stopwatch.stop() break elif delete_status == 0: pass elif delete_status == -1: print "Deletion Failed" break print "Deleted server..." + server min = calculate_obj.getMin(TIME_LIST) max = calculate_obj.getMax(TIME_LIST) avg = calculate_obj.getAverage(TIME_LIST) print "Min: " + str(min) print "Max: " + str(max) print "Average: " + str(avg) dict_return['server'] = SERVER_LIST dict_return['min'] = min dict_return['max'] = max dict_return['avg'] = avg dict_return['name'] = "nova.delete" disp_list.append(dict_return) return disp_list
def run(self, img, step=None, debug=False, print_time=False, filename='unknown'): self.debug_out_list = [] self.source = img funcs_to_run = self.functions[:step] output = self.source stopwatch = Stopwatch() log_string = '{}\t{: <16}\t{:.04f}s {:.02f} fps' for func in funcs_to_run: if debug: output, output_debug = func.run(debug, input=output) self.debug_out_list.append(output_debug) else: output = func.run(debug, input=output) t = stopwatch.round() if print_time: fps = 1 / t if t != 0 else 999 print(log_string.format(filename, str(func), t, fps)) t = stopwatch.total() fps = 1 / t if t != 0 else 999 print(Fore.YELLOW + log_string.format(filename, 'TOTAL', t, fps) + Fore.RESET) print() if print_time else None if debug: return self.debug_out_list[-1] else: return output
def main(): """ Count the number of prime numbers less than two million and time how long it takes. Compares the performance of different algorithms """ from get_positive_number_from_user import get_positive_num player_int = int(get_positive_num()) timer = Stopwatch() print() print(format(' TimeIt - is_prime() ', '*^70')) timer.start() print('{0} Is prime?: {1}'.format(player_int, is_prime(player_int))) timer.stop() print('Time taken = {0:.6f} Seconds'.format(timer.elapsed())) print() print(format(' TimeIt - prime_generator() ', '*^70')) timer.start() prime_gen_obj = prime_generator(0, player_int) timer.stop() print('{0} primes between 0 -> {1}'.format( len([t for t in prime_gen_obj]), player_int)) print('Time taken = {0:.6f} Seconds'.format(timer.elapsed())) print() print(format(' TimeIt - primes_list_comprehension() ', '*^70')) timer.start() primes_list = primes_list_comprehension(player_int) timer.stop() print('{0} primes under {1}'.format(len(primes_list), player_int)) print('Time taken = {0:.6f} Seconds'.format(timer.elapsed())) print()
def add_widgets(self): # Tabbed view self.notebook = ttk.Notebook(self) self.notebook.pack(fill=tk.BOTH, expand=1) self.notebook.bind("<<NotebookTabChanged>>", self.manage_threads) # First Tab: Alarms self.alarms = Alarms(self.notebook) self.protocol("WM_DELETE_WINDOW", self.on_close) self.alarms.pack(fill=tk.BOTH, expand=1) self.notebook.add(self.alarms, text="Alarms") # Second Tab: Clock (Hopefully will add analog and digital) self.clock = Clock(self.notebook) self.clock.pack(fill=tk.BOTH, expand=1) self.notebook.add(self.clock, text="Clock") # Third Tab: Stopwatch self.stopwatch = Stopwatch(self.notebook) self.stopwatch.pack(fill=tk.BOTH, expand=1) self.notebook.add(self.stopwatch, text="Stopwatch") # Fourth Tab: Timer self.timer = Timer(self.notebook) self.timer.pack(fill=tk.BOTH, expand=1) self.notebook.add(self.timer, text="Timer")
def new(self): # start a new game self.timer = Stopwatch() self.all_sprites = pg.sprite.Group() self.platforms = pg.sprite.Group() self.enemies = pg.sprite.Group() self.player = Player(self) self.all_sprites.add(self.player) self.last_update = 0 pg.mixer.music.load(path.join(SOUND, GAME_TRACK)) pg.mixer.music.play(LOOP) pg.mixer.music.set_volume(0.6) self.pausedtime = 0 # Enemies for i in range(0): m = Enemy(self) self.all_sprites.add(m) self.enemies.add(m) # Platforms for plat in PLATFORM_LIST: p = Platform(self, *plat) self.all_sprites.add(p) self.platforms.add(p) # Other platforms self.run()
def __init__(self, model, device): ie = IECore() model_xml = model model_bin = os.path.splitext(model_xml)[0] + ".bin" net = IENetwork(model=model_xml, weights=model_bin) for input_key in net.inputs: if len(net.inputs[input_key].layout) == 4: self.n, self.c, self.h, self.w = net.inputs[input_key].shape assert (len(net.inputs.keys()) == 1 or len(net.inputs.keys()) == 2), "Sample supports topologies only with 1 or 2 inputs" self.out_blob = next(iter(net.outputs)) self.input_name, input_info_name = "", "" for input_key in net.inputs: if len(net.inputs[input_key].layout) == 4: self.input_name = input_key net.inputs[input_key].precision = 'U8' elif len(net.inputs[input_key].layout) == 2: input_info_name = input_key net.inputs[input_key].precision = 'FP32' if net.inputs[input_key].shape[1] != 3 and net.inputs[input_key].shape[1] != 6 or \ net.inputs[input_key].shape[0] != 1: print( 'Invalid input info. Should be 3 or 6 values length.') self.data = {} if input_info_name != "": infos = np.ndarray(shape=(self.n, self.c), dtype=float) for i in range(self.n): infos[i, 0] = self.h infos[i, 1] = self.w infos[i, 2] = 1.0 self.data[input_info_name] = infos output_name, output_info = "", net.outputs[next( iter(net.outputs.keys()))] for output_key in net.outputs: if net.layers[output_key].type == "DetectionOutput": output_name, output_info = output_key, net.outputs[output_key] if output_name == "": print("Can't find a DetectionOutput layer in the topology") output_dims = output_info.shape if len(output_dims) != 4: print("Incorrect output dimensions for SSD model") max_proposal_count, object_size = output_dims[2], output_dims[3] if object_size != 7: print("Output item should have 7 as a last dimension") output_info.precision = "FP32" self.exec_net = ie.load_network(network=net, device_name=device) self.watch = Stopwatch()
def test_largescale(): s = Stopwatch() integration_factor = 5 device_map = device_parser.build_device_map(device_parser.parse_data('test.xml')) test_size = 10000 histogram = OrderedDict() for i in range(5): time = 0.0 for j in range(5): s.start() generate_test_input(device_map, test_size, file_name='test_input1.csv') s.stop() print('Generating test input of size {}: '.format(test_size), s.read()) s.reset() s.start() analyze_data_nograph('csvs/test_input1.csv', integration_factor, device_map) s.stop() print('Processing input of size {}: '.format(test_size), s.read()) time += s.read() s.reset() print('Average time for input of size {}: '.format(test_size), time/5) histogram[test_size] = time/5 test_size *= 2 print(histogram) for i,j in histogram.items(): print(' size | time ') print('{0:5d}|{1:5f}'.format(i,j))
def sieve(n): """ Generates all the prime numbers from 2 to n - 1. n - 1 is the largest potential prime considered. Algorithm originally developed by Eratosthenes. """ timer = Stopwatch() # Record start time timer.start() # Each position in the Boolean list indicates # if the number of that position is not prime: # false means "prime," and true means "composite." # Initially all numbers are prime until proven otherwise nonprimes = n * [False] count = 0 nonprimes[0] = nonprimes[1] = True # Start at the first prime number, 2. for i in range(2, n): if not nonprimes[i]: count += 1 for j in range(2*i, n, i): nonprimes[j] = True timer.slop() print('Count =', count, 'Elapsed time', timer.elapsed(), 'seconds')
def sieve(n): """ Generates all the prime numbers from 2 to n - 1. n - 1 is the largest potential prime considered. Algorithm originally developed by Eratosthenes. """ timer = Stopwatch() timer.start() # Record start time # Each position in the Boolean list indicates # if the number of that position is not prime: # false means "prime," and true means "composite." # Initially all numbers are prime until proven otherwise nonprimes = n * [False] # Global list initialized to all False count = 0 # First prime number is 2; 0 and 1 are not prime nonprimes[0] = nonprimes[1] = True # Start at the first prime number, 2. for i in range(2, n): # See if i is prime if not nonprimes[i]: count += 1 # It is prime, so eliminate all of its # multiples that cannot be prime for j in range(2*i, n, i): nonprimes[j] = True # Print the elapsed time timer.stop() print("Count =", count, "Elapsed time:", timer.elapsed(), "seconds")
def testDuration(self): """Tests that the duration results works as expected""" stopwatch = Stopwatch() time.sleep(1) stopwatch.stop() self.assertTrue(stopwatch.duration >= 1)
def run_mad_anom_detection_flow(file_path, block_size=30): data = data_loader.load_data(file_path) data_flow = data_it(data, block_size) sw = Stopwatch() sw.start() df = [] try: for data_block in data_flow: outerliner = get_mad_outlier(data_block) df.append(outerliner) except StopIteration as ex: print(ex) sw.stop() print(sw.duration) columns = ['max', 'min', 'raw', 'ts', 'med'] df = DataFrame(df, columns=columns) plt.fill_between(df['ts'].values, df['max'].values, df['min'].values, color='lightgray') plt.plot(df['ts'].values, df['raw'].values) plt.plot(df['ts'].values, df['med'].values) for i in range(len(df)): raw_row = df.values[i] if raw_row[2] < raw_row[1] or raw_row[2] > raw_row[0]: plt.plot(raw_row[3], raw_row[2], 'ro') plt.show()
def timeTrial(n): a = stdarray.create1D(n, 0) for i in range(n): a[i] = stdrandom.uniformInt(-1000000, 1000000) watch = Stopwatch() count = threesum.countTriples(a) return watch.elapsedTime()
def test_get_face_rate(self, ): # Arrange max_process = 4 batch_data: BatchData = batch_data_loader_service.load_batch(0) logger.info("Got batch data.") stopwatch = Stopwatch() stopwatch.start() num_videos = 1 # batch_data.size() for i in range(num_videos): logger.info(f"Getting {i}th video.") vid_path = batch_data.get_candidate_file_path(i) fil = video_service.process_all_video_frames( vid_path, face_recog_service.get_face_data, max_process) stopwatch.stop() for fi in fil: landmarks = fi['face_info_landmarks'] frame_index = fi['frame_index'] file_path = fi['file_path'] for ndx, land in enumerate(landmarks): face_image = land['face_image'] image_service.show_image(face_image, 'test') par_path = os.path.join(config.TRASH_PATH, f"{file_path.stem}") os.makedirs(par_path, exist_ok=True) image_path = os.path.join(par_path, f"{frame_index}_{ndx}.png") logger.info(f"Writing to {image_path}.") image_converted = cv2.cvtColor(face_image, cv2.COLOR_BGR2RGB) cv2.imwrite(image_path, image_converted) logger.info(stopwatch)
def __init__(self, model): # Initialize TRT environment self.input_shape = (300, 300) trt_logger = trt.Logger(trt.Logger.INFO) trt.init_libnvinfer_plugins(trt_logger, '') with open(model, 'rb') as f, trt.Runtime(trt_logger) as runtime: engine = runtime.deserialize_cuda_engine(f.read()) self.host_inputs = [] self.cuda_inputs = [] self.host_outputs = [] self.cuda_outputs = [] self.bindings = [] self.stream = cuda.Stream() for binding in engine: size = trt.volume( engine.get_binding_shape(binding)) * engine.max_batch_size host_mem = cuda.pagelocked_empty(size, np.float32) cuda_mem = cuda.mem_alloc(host_mem.nbytes) self.bindings.append(int(cuda_mem)) if engine.binding_is_input(binding): self.host_inputs.append(host_mem) self.cuda_inputs.append(cuda_mem) else: self.host_outputs.append(host_mem) self.cuda_outputs.append(cuda_mem) self.context = engine.create_execution_context() self.watch = Stopwatch()
async def version(ctx: commands.Context): Console.printc(f"user: {ctx.author} Started version", Fore.LIGHTBLUE_EX) sw = Stopwatch() await send_msg(ctx, f"```yaml\nVersion: {VERSION}\n```") Console.log("SYS (version)", f"Total time taken: {round(sw.duration * 1000)} ms") sw.reset()
async def help(ctx: commands.Context): Console.printc(f"user: {ctx.author} Started help", Fore.LIGHTBLUE_EX) sw = Stopwatch() await ctx.send(f"Help: ```{tabulate(HELP_LIST, headers=[' ', ' '], stralign='left', tablefmt='plain')}```") Console.log("SYS (help)", f"Total time taken: {round(sw.duration * 1000)} ms") sw.reset()
def testRunning(self): """Tests that the running boolean works as expected""" stopwatch = Stopwatch() self.assertTrue(stopwatch.running) stopwatch.stop() self.assertFalse(stopwatch.running) stopwatch.restart() self.assertTrue(stopwatch.running)
def testDigits(self): """Tests that the string contains the correct precision""" stopwatch = Stopwatch(4) time.sleep(1) stopwatch.stop() # e.g 5.7282s self.assertTrue(len(str(stopwatch)) == 7)
def __init__(self, robot, duration, speed, name=None, timeout=15): """Constructor""" super().__init__(name, timeout) self.robot = robot self.requires(robot.drivetrain) self._stopwatch = Stopwatch() self._duration = duration self._speed = speed
def time_trial(n): a = [] for i in range(0, n): a.append(random.randint(-MAXIMUM_INTEGER, MAXIMUM_INTEGER)) stopwatch = Stopwatch() ThreeSum.count(a) return stopwatch.elapsed_time()
def testStop(self): """Tests stopwatch's stopped state""" stopwatch = Stopwatch() stopwatch.stop() now = str(stopwatch) time.sleep(0.1) after = str(stopwatch) # A stopped stopwatch should not move self.assertEqual(now, after)
def __init__(self, resources: Resources) -> None: self.camera = Vector2d(0, 0) self.stopwatch = Stopwatch(resources) # Objective 4: Create a Player self.player = Player(resources) # Objective 5: Create a Map self.map = Map(resources)
def solve_it(input_data, prev_sol=None, iterations=10000): lines = input_data.split('\n') first_line = lines[0].split() node_count = int(first_line[0]) edge_count = int(first_line[1]) adj = [[] for _ in range(node_count)] for i in range(1, edge_count + 1): line = lines[i] parts = line.split() u, v = int(parts[0]), int(parts[1]) adj[u].append(v) adj[v].append(u) # start with blank solution which is sorted by the first permutation solution = list(0 for _ in range(node_count)) # load in previous solution if file location given if prev_sol: solution = prev_sol stopwatch_greedy = Stopwatch() stopwatch_greedy.stop() stopwatch_permute = Stopwatch() stopwatch_permute.stop() for i in range(1, iterations + 1): if i % 10 == 0: with open("progress.txt", 'w') as f: f.write(str(i) + " iterations, " + str(max(solution) + 1) + " colors") stopwatch_permute.start() nodes = permute_nodes(node_count, solution, adj) stopwatch_permute.stop() stopwatch_greedy.start() solution = greedy(node_count, nodes, adj) stopwatch_greedy.stop() print("greedy running time: " + str(stopwatch_greedy)) print("permute running time: " + str(stopwatch_permute)) return stringify(solution)
def timeTrials(f, n, trials): total = 0.0 a = stdarray.create1D(n, 0.0) for t in range(trials): for i in range(n): a[i] = stdrandom.uniformFloat(0.0, 1.0) watch = Stopwatch() f(a) total += watch.elapsedTime() return total
def main(): killhandler = KillHandler() reddit = praw.Reddit(client_id=config.client_id, client_secret=config.client_secret, username=config.username, password=config.password, user_agent=config.user_agent) logging.info("Starting checking submissions...") stopwatch = Stopwatch() while not killhandler.killed: try: for submission in reddit.subreddit('+'.join( config.subreddits)).stream.submissions(skip_existing=True): duration = stopwatch.measure() logging.info(f"New submission: {submission}") logging.info(f" -- retrieved in {duration:5.2f}s") # We don't need to post a sticky on stickied posts if submission.stickied: logging.info(f" -- skipping (stickied)") continue # Post a comment to let people know where to invest bot_reply = submission.reply_wrap(message.invest_place_here) # Sticky the comment if config.is_moderator: bot_reply.mod.distinguish(how='yes', sticky=True) # Measure how long processing took duration = stopwatch.measure() logging.info(f" -- processed in {duration:5.2f}s") if killhandler.killed: logging.info("Termination signal received - exiting") break except prawcore.exceptions.OAuthException as e_creds: traceback.print_exc() logging.error(e_creds) logging.critical("Invalid login credentials. Check your .env!") logging.critical( "Fatal error. Cannot continue or fix the problem. Bailing out..." ) exit() except Exception as e: logging.error(e) traceback.print_exc() time.sleep(10)
def testStopwatch(self): """Tests stopwatch timing""" stopwatch = Stopwatch() time.sleep(0.1) stopwatch.stop() m = str(stopwatch) # Can't gurantee exact timings as python speed may differ each execution # so ensure it is atleast a 100ms # also a test for friendly time string self.assertTrue(m.startswith("100") and m.endswith("ms"))