Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- import operator
- import cProfile
- import sys
- def load_files():
- with open('vlans.csv') as f:
- f.readline()
- d = f.read()[:-1]
- vlans = [l.split(",") for l in d.split("\n")]
- with open('requests.csv') as f:
- f.readline()
- d = f.read()[:-1]
- requests = [l.split(",") for l in d.split("\n")]
- return vlans, requests
- def process(vlans, requests, output_rows=0):
- out = []
- by_vlan_id = sorted(sorted(vlans, key=lambda x: int(x[0])), key=lambda x: int(x[2]))
- # by_vlan_id = sorted(vlans, key=lambda x: (int(x[2]), int(x[0]))) # Slower than the above! But more readable.
- red_vlans_iter = iter(by_vlan_id)
- no_red_vlans_iter = iter(by_vlan_id)
- for reqn, red in iter(requests):
- if red == "1":
- dev_id, vlan_id, primary, secondary = None, None, None, None
- for info in red_vlans_iter:
- if not info[2]:
- continue
- if dev_id is None or info[0] != dev_id or info[2] != vlan_id:
- dev_id = info[0]
- vlan_id = info[2]
- primary, secondary = None, None
- if info[1] == "1":
- primary = info
- else:
- secondary = info
- if primary is not None and secondary is not None:
- primary[2] = 0
- secondary[2] = 0
- break
- out.append("%s,%s,0,%s\n%s,%s,1,%s" % (reqn, dev_id, vlan_id, reqn, dev_id, vlan_id))
- else:
- for info in no_red_vlans_iter:
- if info[2] and info[1] == "1":
- out.append("%s,%s,1,%s" % (reqn, info[0], info[2]))
- info[2] = 0
- break
- return out
- def main(silent=False):
- t0 = time.perf_counter()
- vlans, requests = load_files()
- t1 = time.perf_counter()
- out = process(vlans, requests)
- t2 = time.perf_counter()
- with open("output_py.csv", 'w') as f:
- f.write('request_id,device_id,primary_port,vlan_id\n')
- f.write("\n".join(out))
- t3 = time.perf_counter()
- if not silent:
- print("total %.2fms: reading: %dms, processing: %dms, writing: %dms" % (
- (t3 - t0) * 1000, (t1 - t0) * 1000, (t2 - t1) * 1000, (t3 - t2) * 1000))
- return (t3 - t0) * 1000
- if __name__ == "__main__":
- if len(sys.argv) > 1:
- if sys.argv[1] == "profile":
- sortby = sys.argv[2] if len(sys.argv) > 2 else 'tottime'
- cProfile.run("main()", sort=sortby)
- elif sys.argv[1] == "avg":
- n = int(sys.argv[2]) if len(sys.argv) > 2 else 20
- cumul = 0
- for i in range(n):
- print("%d/%d\r" % (i, n), end="")
- cumul += main(True)
- print("Average over %d executions: %.3fms" % (n, cumul / n))
- else:
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement