def greedy_dc(model: Model) -> (float, int, float, float): """ Greedy thought: Sort sfcs by its computing resources consumption in the increasing order. For every sfc, sort each available configuration by its latency in the increasing order. Find the first path whose resources can fulfill the requirement of sfc. If no available path is found, reject the sfc! """ print(">>> Greedy Start <<<") topo = copy.deepcopy(model.topo) sfcs = model.sfc_list[:] sfcs.sort(key=lambda x: x.computing_resources_sum) with Timer(verbose_msg=f'[Greedy] Elapsed time: {{}}'), PixelBar( "SFC placement") as bar: bar.max = len(sfcs) for sfc in sfcs: configuration = generate_configuration_greedy_dfs(topo, sfc) if configuration and is_configuration_valid( topo, sfc, configuration): sfc.accepted_configuration = configuration bar.next() obj_val = objective_value(model) accept_sfc_number = len(model.get_accepted_sfc_list()) latency = average_latency(model) print("Objective Value: {} ({}, {}, {})".format(obj_val, evaluate(model), accept_sfc_number, latency)) return obj_val, accept_sfc_number, latency, model.compute_resource_utilization( )
def test_sat_composition_performance(PurchaseComposition): t = Timer() print("SAT (composition): ") print('Protocol, Property, Min, Mean, Max, Times') properties = { "Liveness": lambda P: P.is_live(), "Safety": lambda P: P.is_safe() } perf_test([PurchaseComposition.protocols['Refined-Commerce']], properties)
def PARC(model: Model): """ 1. Sort SFCs by its computing resources in the ascending order. 2. For every sfc, compute its merged chain. 3. Find the first path whose resources can fulfill the requirement of sfc. 4. If so, accept the configuration 5. Otherwise, try to find the path for the origin sfc 6. If so, accept the configuration 7. Otherwise, refuse the sfc """ print(">>> Para Greedy Start <<<") topo = copy.deepcopy(model.topo) sfcs = model.sfc_list[:] sfcs.sort(key=lambda sfc: sfc.computing_resources_sum) with Timer(verbose_msg=f'[ParaGreedy] Elapsed time: {{}}'), PixelBar( "SFC placement") as bar: bar.max = len(sfcs) for sfc in sfcs: optimal_sfc = SFC(sfc.pa.opt_vnf_list[:], sfc.latency, sfc.throughput, sfc.s, sfc.d, sfc.idx) optimal_config = generate_configuration_greedy_dfs( topo, optimal_sfc) if optimal_config: # generate origin "place" from the merged "place" merged_vnf_index = 0 place = [optimal_config.place[0]] for para in sfc.pa.opt_strategy: if para == 0: merged_vnf_index += 1 place.append(optimal_config.place[merged_vnf_index]) configuration = Configuration(sfc, optimal_config.route, place, optimal_config.route_latency, optimal_config.idx) if is_configuration_valid(topo, sfc, configuration): sfc.accepted_configuration = configuration if not sfc.accepted_configuration: configuration = generate_configuration_greedy_dfs(topo, sfc) if configuration and is_configuration_valid( topo, sfc, configuration): sfc.accepted_configuration = configuration # else reject bar.next() obj_val = objective_value(model) accept_sfc_number = len(model.get_accepted_sfc_list()) latency = average_latency(model) print("Objective Value: {} ({}, {}, {}, {})".format( obj_val, evaluate(model), accept_sfc_number, latency, model.compute_resource_utilization())) return obj_val, accept_sfc_number, latency, model.compute_resource_utilization( )
def test_single_sub_performance(PurchaseComposition): t = Timer() print("SAT (single sub): ") print('Protocol, Property, Min, Mean, Max, Times') specs = [ 'sub-buyer-starts.bspl', 'sub-pay-first.bspl', 'sub-single-lookup.bspl' ] for s in specs: P = load_file('samples/bspl/performance/' + s).protocols['Refined-Commerce'] properties = {"Liveness": P.is_live, "Safety": P.is_safe} for name, fn in properties.items(): times = [] for x in range(10 + 1): t.tic() fn() t.toc() if x > 0: # burn in once times.append(t.elapsed * 1000) # use milliseconds mean = sum(times) / len(times) print( f"{s}, {name}, {int(min(times))}, {int(mean)}, {int(max(times))}, {times}" )
def test_sat_subprotocol_performance(PurchaseComposition): t = Timer() print("SAT (components): ") print('Protocol, Property, Min, Mean, Max') for P in PurchaseComposition.protocols.values(): if 'Commerce' in P.name: continue properties = { "Enactability": P.is_enactable, "Liveness": P.is_live, "Safety": P.is_safe } for name, fn in properties.items(): times = [] for x in range(10): t.tic() fn() t.toc() print(t.elapsed) times.append(t.elapsed * 1000) # use milliseconds mean = sum(times) / len(times) print( f"{P.name}, {name}, {int(min(times))}, {int(mean)}, {int(max(times))}" )
def consistent(*statements, exhaustive=False): options = arg_parser.parse_known_args()[0] # apparently returns a tuple stats["statements"] += logic.count(statements) statements = [logic.compile(s) for s in statements] clauses = statements cons = [] t = Timer() t.tic() if options.exhaustive or exhaustive: cons += exhaustive_consistency(statements) result = solve(clauses + cons, options, depth="exhaustive") else: depth = int(options.depth) for d in range(depth): cons = consistency(clauses + cons) result = solve(clauses + cons, options, depth) while result and cycle(result): depth += 1 cons = consistency(clauses + cons) result = solve(clauses + cons, options, depth) t.toc() stats["time"] += t.elapsed return result
def test_clear_timers(self): """Test clear timers""" t = Timer(matlab_like=False) for i in range(10): t.start(i) t.clear_timers() assert len(t._timers_start) == 0, "Timers not restarting"
def perf_test(objects, properties): t = Timer() for obj in objects: for name, fn in properties.items(): times = [] for x in range(10 + 1): t.tic() fn(obj) t.toc() if x > 0: # burn in once times.append(t.elapsed * 1000) # use milliseconds mean = sum(times) / len(times) print( f"{obj.name}, {name}, {int(min(times))}, {int(mean)}, {int(max(times))}, {times}" )
def test_refinement_performance(PurchaseComposition): t = Timer() print("Refinement: ") print("Protocol, Min, Avg, Max") Ps = ['Either-Starts', 'Lookup-Prices', 'Flexible-Payment'] Qs = ['Buyer-Starts', 'Single-Lookup', 'Pay-First'] for i, name in enumerate(Ps): P = PurchaseComposition.protocols[Ps[i]] Q = PurchaseComposition.protocols[Qs[i]] times = [] for x in range(10): t.tic() refines(UoD(), P.public_parameters, Q, P) t.toc() times.append(t.elapsed * 1000) avg = sum(times) / len(times) print( f"{P.name}, {int(min(times))}, {int(avg)}, {int(max(times))}, {times}" )
def test_error_not_initialized_non_matlab_like_key(self): """Test the error when timer has been not initialized""" t = Timer(matlab_like=False) with pytest.raises(TimerError): assert t.stop("init")
def test_error_not_initialized(self): """Test the error when timer has been not initialized""" t = Timer(matlab_like=True) with pytest.raises(TimerError): assert t.stop()
time.sleep(1) elapsed = toc() print("Elapsed time:", elapsed) print("\nNested Tic Toc") tic() for i in range(2): tic() time.sleep(1) elapsed = toc() print("[IN LOOP] Elapsed time:", elapsed) print("[OUT LOOP] Elapsed time:", toc()) print("\n>>>Using Timer class") print("\nSimple") t = Timer() t.start() time.sleep(1) elapsed = t.stop() print("Elapsed time:", elapsed) print("\nNested") t.start() for i in range(2): t.start() time.sleep(1) elapsed = t.stop() print("[IN LOOP] Elapsed time:", elapsed) print("[OUT LOOP] Elapsed time:", t.stop()) print(">>> Tic Toc, v2 (non matlab-like)")
def linear_programming(model: Model) -> (float, int, float, float): print(">>> Start LP <<<") problem = LpProblem("VNF Placement", LpMaximize) with Timer(verbose_msg=f'[GenC] Elapsed time: {{}}'), PixelBar( "Generating configuration sets") as bar: bar.max = len(model.sfc_list) for sfc in model.sfc_list: sfc.configurations = generate_configurations(model.topo, sfc) for configuration in sfc.configurations: configuration.var = LpVariable(configuration.name, 0, 1, LpContinuous) bar.next() # total number of valid sfc config_num = sum(len(sfc.configurations) for sfc in model.sfc_list) valid_sfc_num = sum(len(sfc.configurations) > 0 for sfc in model.sfc_list) print("Number of LP Variables: {}\tValid SFC: {}".format( config_num, valid_sfc_num)) with Timer(verbose_msg=f'[LP Solving] Elapsed time: {{}}'): # Objective function problem += lpSum( (configuration.var for configuration in sfc.configurations) for sfc in model.sfc_list), "Total number of accepted requests" # Constraints # basic constraints for sfc in model.sfc_list: problem += lpSum(configuration.var for configuration in sfc.configurations) <= 1.0, "Basic_{}".format( sfc.idx) # computing resource constraints for index, info in model.topo.nodes.data(): problem += lpSum( configuration.var * configuration.computing_resource[index] for sfc in model.sfc_list for configuration in sfc.configurations if index in configuration.computing_resource ) <= info['computing_resource'], "CR_{}".format(index) # throughput constraints for start, end, info in model.topo.edges.data(): problem += lpSum( configuration.var * sfc.throughput * configuration.edges[(start, end)] for sfc in model.sfc_list for configuration in sfc.configurations if (start, end) in configuration.edges) <= info['bandwidth'], "TP_{}_{}".format( start, end) problem.solve() config.K = max(config.K / 3 * 2, config.K_MIN) obj_val = value(problem.objective) accept_sfc_number = sum( len(sfc.configurations) > 0 for sfc in model.sfc_list) latency = 0 if accept_sfc_number is not 0: latency = sum( configuration.get_latency() * configuration.var.varValue for sfc in model.sfc_list for configuration in sfc.configurations) / accept_sfc_number print("Objective Value: {}({}, {}ms)".format(obj_val, accept_sfc_number, latency)) return obj_val, accept_sfc_number, latency, model.compute_resource_utilization( )