当前位置:   article > 正文

用Python实现简单的边缘计算框架_边缘计算相关源码有哪些

边缘计算相关源码有哪些
  1. import random
  2. import simpy
  3. # 定义边缘计算服务器
  4. class EdgeServer:
  5. def __init__(self, env, id, cpu_capacity, gpu_capacity):
  6. self.env = env
  7. self.id = id
  8. self.cpu_capacity = cpu_capacity
  9. self.gpu_capacity = gpu_capacity
  10. self.cpu_available = cpu_capacity
  11. self.gpu_available = gpu_capacity
  12. # 分配计算资源
  13. def allocate(self, task):
  14. if task.is_gpu and self.gpu_available >= task.requirement:
  15. self.gpu_available -= task.requirement
  16. return True
  17. elif not task.is_gpu and self.cpu_available >= task.requirement:
  18. self.cpu_available -= task.requirement
  19. return True
  20. else:
  21. return False
  22. # 释放计算资源
  23. def release(self, task):
  24. if task.is_gpu:
  25. self.gpu_available += task.requirement
  26. else:
  27. self.cpu_available += task.requirement
  28. # 定义任务
  29. class Task:
  30. def __init__(self, env, id, requirement, is_gpu):
  31. self.env = env
  32. self.id = id
  33. self.requirement = requirement
  34. self.is_gpu = is_gpu
  35. self.start_time = None
  36. self.end_time = None
  37. # 执行任务
  38. def execute(self, edge_server):
  39. self.start_time = self.env.now
  40. yield self.env.timeout(random.uniform(0, 1))#模拟处理时延.
  41. self.end_time = self.env.now
  42. execution_time = self.end_time - self.start_time
  43. print("Task {} executed on edge server {} in {:.2f} seconds (start time: {:.2f}, end time: {:.2f})".format(
  44. self.id, edge_server.id, execution_time, self.start_time, self.end_time))
  45. edge_server.release(self)
  46. # 定义仿真环境
  47. class Simulator:
  48. def __init__(self, num_servers, cpu_capacity, gpu_capacity, num_tasks, task_requirement):
  49. self.env = simpy.Environment()
  50. self.servers = [EdgeServer(self.env, i, cpu_capacity, gpu_capacity) for i in range(num_servers)]
  51. self.tasks = [Task(self.env, i, task_requirement, random.choice([True, False])) for i in range(num_tasks)]
  52. self.env.process(self.run())
  53. # 任务调度
  54. def schedule(self):
  55. for task in self.tasks:
  56. allocated = False
  57. for server in self.servers:
  58. if server.allocate(task):
  59. allocated = True
  60. self.env.process(task.execute(server))
  61. break
  62. if not allocated:
  63. print("Task {} cannot be executed due to insufficient resources".format(task.id))
  64. # 运行仿真
  65. def run(self):
  66. while True:
  67. yield self.env.timeout(1)
  68. self.schedule()
  69. # 运行仿真
  70. simulator = Simulator(3, 10, 5, 10, 2)
  71. simulator.env.run(until=10)

该代码能实现简单的边缘计算,并且输出任务的执行时刻和截止时刻

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/344659?site
推荐阅读
相关标签
  

闽ICP备14008679号