def ekf_analysis(): time = 0.0 # State Vector [x y yaw v]' xEst = np.zeros((4, 1)) xTrue = np.zeros((4, 1)) PEst = np.eye(4) xDR = np.zeros((4, 1)) # Dead reckoning # history hxEst = xEst hxTrue = xTrue hxDR = xTrue hz = np.zeros((2, 1)) # Contadores para o Loop process_loop_init = pt() # Contador de processo script_loop_init = timeit.default_timer() # Contador Benchmark while SIM_TIME >= time: print('SIMULATION assigned to thread:' + '{}'.format(threading.current_thread().name)) time += DT schedule.run_pending() u = calc_input() xTrue, z, xDR, ud = observation(xTrue, xDR, u) xEst, PEst = ekf_estimation(xEst, PEst, z, ud) # store data history hxEst = np.hstack((hxEst, xEst)) hxDR = np.hstack((hxDR, xDR)) hxTrue = np.hstack((hxTrue, xTrue)) hz = np.hstack((hz, z)) if show_animation: plt.cla() plt.plot(hz[0, :], hz[1, :], ".g") plt.plot(hxTrue[0, :].flatten(), hxTrue[1, :].flatten(), "-b") plt.plot(hxDR[0, :].flatten(), hxDR[1, :].flatten(), "-k") plt.plot(hxEst[0, :].flatten(), hxEst[1, :].flatten(), "-r") plot_covariance_ellipse(xEst, PEst) plt.axis("equal") plt.grid(True) plt.pause(0.001) # Finalização dos Contadores Loop process_loop = pt() - process_loop_init script_loop = timeit.default_timer() - script_loop_init print("--------------------------------------------------") print("Tempo do Processo Loop: ", process_loop) print("Tempo do Script: Loop: ", script_loop, "\n") plot()
def run(x, reps): objs = [Obj() for _ in range(max_x)] col = [(i, (objs[randrange(x)],)) for i in range(n_ops)] t1 = pt() for _ in range(reps): for (i, (o,)) in col: pass t2 = pt() return t2 - t1
def timer(pre = None, func = None, post = None, n = 1): suma, t = 0.0, 0 a = lambda x: (lambda: _) if x is None else x pre, func, post = a(pre), a(func), a(post) for _ in range(n): pre() temp = pt() func() suma += pt() - temp post() return suma/n
def simulate_serial(): print('Iniciando Modo Serial:') process_init = pt() # Contador de processo script_init = timeit.default_timer() # Contador Benchmark simulation.main() process_end = pt() - process_init script_end = timeit.default_timer() - script_init print('Tempo de Finalização do Processo (Serial): ', process_end) print('Tempo de Finalização do Script (Serial): ', script_end) print('--------------------------')
def simulate_threading(): # Contadores print('Iniciando Multithreading:\n') process_init = pt() # Contador de processo script_init = timeit.default_timer() # Contador Benchmark with ThreadPoolExecutor(max_workers=None) as executor: executor.map(simulation.main()) # task2 = executor.map(cpu_data.main()) process_end = pt() - process_init script_end = timeit.default_timer() - script_init print('Tempo de Finalização do Processo (Threading): ', process_end) print('Tempo de Finalização do Script (Threading): ', script_end) print('--------------------------')
def __init__(self, currentSpeed, maxSpeed, rate): self.startSpeed = currentSpeed self.currentSpeed = currentSpeed self.maxSpeed = maxSpeed self.rate = rate self.startTime = pt() self.loopAcc = True
def accelerate(self) -> float: if self.currentSpeed < self.maxSpeed: self.currentSpeed += self.rate elif self.currentSpeed == self.maxSpeed and self.loopAcc: self.time = pt() - self.startTime self.loopAcc = False return self.currentSpeed
def main(): print(__file__ + " start!!") ekf_analysis() process_end = pt() - process_init script_end = timeit.default_timer() - script_init print("----------------FINAL DA SIMULAÇÃO----------------") print("Tempo do Processo Total: ", process_end) print("Tempo do Script: Main: ", script_end, "\n") print("--------------------------------------------------")
def main(): print(__file__ + " start!!") with ProcessPoolExecutor(max_workers=None) as executor: executor.submit(ekf_analysis) process_end = pt() - process_init script_end = timeit.default_timer() - script_init print("----------------FINAL DA SIMULAÇÃO----------------") print("Tempo do Processo Total: ", process_end) print("Tempo do Script: Main: ", script_end, "\n") print("--------------------------------------------------")
def Main(): coords = [ReturnPos(line) for line in lines] limits = GetMax(coords) while (limits[2] - limits[3]) > 19 and (limits[0] - limits[1]) > 60: limits = RunRoutine(coords) RunRoutine2(coords) print('Part 2 =', count) print('Ran for ', pt(), 'seconds') return coords
def process_log(start_time, process_time, log_traces, activities): # geração de arquivo com algumas variáveis uteis à análise da execução process_end = pt() - process_time log_size = len(log_traces) activities_size = len(activities) log_messages = [ f'Execution start: \t{start_time}', f'Total instances: \t{log_size} cases', f'Total activities:\t{activities_size}', f'Process Time: \t{process_end:.3f}ms' ] with open('process_log.txt', 'a') as file: for message in log_messages: print(message) file.write(f'{message}\n') file.close()
import numpy as np import math import matplotlib.pyplot as plt import psutil as psu import timeit import time from time import process_time as pt import plotly.graph_objs as go import plotly.offline from plotly import tools import threading # Contadores process_init = pt() # Contador de processo script_init = timeit.default_timer() # Contador Benchmark # Alocação de Memória para Variáveis Utilizadas no Plot cpu_dicc = {'cpu1': [], 'cpu2': [], 'cpu3': [], 'cpu4': []} time_dicc = {'time': []} memory_dicc = {'memory': []} # Estimation parameter of EKF Q = np.diag([0.1, 0.1, np.deg2rad(1.0), 1.0])**2 # predict state covariance R = np.diag([1.0, 1.0])**2 # Observation x,y position covariance # Simulation parameter Qsim = np.diag([1.0, np.deg2rad(30.0)])**2 Rsim = np.diag([0.5, 0.5])**2 DT = 0.1 # time tick [s] SIM_TIME = 50.0 # simulation time [s]
from time import process_time as pt from primes import primes_until print(pt()) print(sum(primes_until(2000000))) print(pt())
from itertools import combinations from functools import reduce from time import process_time as pt t = pt() with open('input.txt') as f: packages = list(map(int, f.readlines())) all_loads = sum(packages) done = False i = 1 p1 = p2 = 2**63 while not done: for c in combinations(packages, i): if sum(c) * 4 == all_loads: p2 = min(p2, reduce(lambda x, y: x * y, c)) if sum(c) * 3 == all_loads: p1 = min(p1, reduce(lambda x, y: x * y, c)) done = True i += 1 t = pt() - t print("Problem 1: %d"%p1) print("Problem 2: %d"%p2) print("Time elapsed: %d ms"%int(t * 1000))
log_size = len(log_traces) activities_size = len(activities) log_messages = [ f'Execution start: \t{start_time}', f'Total instances: \t{log_size} cases', f'Total activities:\t{activities_size}', f'Process Time: \t{process_end:.3f}ms' ] with open('process_log.txt', 'a') as file: for message in log_messages: print(message) file.write(f'{message}\n') file.close() if __name__ == '__main__': start_time = datetime.now() process_time = pt() log_file_path = 'simulation_logs.csv' petrinet_png_file = 'petrinet.png' if len(sys.argv) > 1: log_file_path = sys.argv[1] if len(sys.argv) > 2: petrinet_png_file = sys.argv[2] log_traces = read_log_file(log_file_path) activities = execute_alpha_miner(log_traces, petrinet_png_file) process_log(start_time, process_time, log_traces, activities)
deðiþenAðýrlýklar = [Fraction (1, 11) for _ in range (len (amazonAdaylar))] """ deðiþenAðýrlýklar = np.full(11, 1 / len(amazonAdaylar)) PytheussesFavorileri = {"Iokaste", "Medousa", "Sofronia", "Andromeda"} try: kere = abs(int(input("Hergün seçilecek 4'lü çekiliþ sayýsý [1 000]? "))) except: kere = 1000 sayaç = 0 ihtimal = 1 / 330 # %03 (binde 3)... geçenGünler = 0 faktör1 = 1 / 13 # Hergün favori olmayan ilk yediliden düþülecek aðýrlýk... faktör2 = 1 / 12 # Hergün favori son dörtlüsüne eklenecek aðýrlýk... baþlat = pt() print("\nBaþlangýç aðýrlýklar: %", [int(a * 10000) / 100 for a in deðiþenAðýrlýklar]) while ihtimal < 0.9: # yüzde 90 (hergün 1 döngü)... for i in range( kere ): # Ýstenen, 1000 tesadüfi seçimden enaz 900 favori dörtlü kümesi çýkmasý... seçilenDörtlü = aðýrlýklýÖrnekleme2(amazonAdaylar, deðiþenAðýrlýklar, 4) if set(seçilenDörtlü) == PytheussesFavorileri: sayaç += 1 ihtimal = sayaç / kere # ihtimal=900/1000: son... sayaç = 0 deðiþenAðýrlýklar[:7] = [ aðýr - aðýr * faktör1 for aðýr in deðiþenAðýrlýklar[:7] ]
def runtime(function): time = pt() function() print(f'Runtime: {pt() - time} seconds')
#시간 카운팅 -> timeit 필요 from time import time as pt #리스트 초기화 words: list[str] = [ "cat", "dog", "fox", "raptor", "whale", "butterfly", "snake", "monkey", "elephant", "frog" ] st: float #시작 시간 기록 tries: int = 0 #시도 횟수 word: str = "" #선정된 문자 #시작 대기 input("준비되었으면 Enter를 누르세요") #타이머 초기화 st = pt() #메인루프 -> break로만 빠져나올 수 있음 while True: #문제 구문 tries += 1 while True: #한번 더 -> 틀리면 되돌아오게 word = random.choice(words) print(word) if (input() == word): break if (tries >= 5): #5회 완료하였다면 종료 break print("소모시간 : %.2fs" % (pt() - st))
i[0] = [i[0][0] + i[1][0], i[0][1] + i[1][1]] self.count += 1 def RunRoutine(self): self.MoveCoordinates(self.coords) self.getmax(self.coords) return self.limits def RunRoutine2(self): print('xrange is ', self.limits[0]-self.limits[1], 'and y range is', self.limits[2]-self.limits[3]) self.MoveCoordinates(self.coords) self.getmax(self.coords) print('xrange is ', self.limits[0]-self.limits[1], 'and y range is', self.limits[2]-self.limits[3]) dMap = dd(tuple) self.placeCoords(dMap) self.printMap(dMap) [print('') for i in range(2)] return 0 def Main(self): while self.limits[2] - self.limits[3] > 19 and self.limits[0] - self.limits[1] > 60: self.RunRoutine() self.RunRoutine2() return self.count t = TestClass() t.Main() print('Part 2 =', t.count) print('Ran for ', pt(), 'seconds')
# import sys # from AVL_Tree import * from handle_csv import fill_csv, extract_csv # from AVL_Node import AVL_Node from time import process_time as pt # from math import log def giveanumber(): size = int(input("Enter size of N: ")) while size <= 0: size = int(input("Enter size of N (greater than zero this time): ")) return size # N = giveanumber() # fill_csv(10) tree = extract_csv() # print(tree) # requires "pretty print tree.txt" code time = pt() # time elapsed since start of program time = pt() - time # print("Elapsed time is:",time) results = tree.range_query() for i in results: print(i)
letter = 0 mini = 0 for c in base: tempx = abs(base[c][0] - i[0]) tempy = abs(base[c][1] - i[1]) result = (tempx + tempy) if result == mini: letter = '.' elif result < mini or mini == 0: mini = result letter = c map[i] = letter.lower() if letter != '.': count[letter] = count[letter] + 1 else: pass #Part of the prompt of this fake map we are filling out involves bases radiating outwards. But we are not supposed to count letters that radiate to the edge of the map, as they are #considered infinite. So this block deletes infinite letters from the overall count for i in map: if i[0] in [xr - 1, 0] or i[1] in [yr - 1, 0]: try: del count[map[i].upper()] except: pass #Now, since we were counting every letter as it was added, we just sort the list by largest, and print that number print('part 1 answer is', count[sorted(count, key=count.get, reverse=True)[0]] + 1) print('Part 1 of program was up forProgram was up for', pt(), 'seconds')