Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines for 2022.
[simgrid.git] / examples / python / exec-cpu-nonlinear / exec-cpu-nonlinear.py
1 # Copyright (c) 2006-2022. The SimGrid Team. All rights reserved.
2 #
3 # This program is free software; you can redistribute it and/or modify it
4 # under the terms of the license (GNU LGPL) which comes with this package.
5
6 # This example shows how to simulate a non-linear resource sharing for
7 # CPUs.
8
9
10 from simgrid import Actor, Engine, NetZone, Host, this_actor
11 import sys
12 import functools
13
14
15 def runner():
16     computation_amount = this_actor.get_host().speed
17     n_task = 10
18
19     this_actor.info("Execute %d tasks of %g flops, should take %d second in a CPU without degradation. It will take the double here." % (
20         n_task, computation_amount, n_task))
21     tasks = [this_actor.exec_init(computation_amount).start()
22              for _ in range(n_task)]
23
24     this_actor.info("Waiting for all tasks to be done!")
25     for task in tasks:
26         task.wait()
27
28     this_actor.info("Finished executing. Goodbye now!")
29
30
31 def cpu_nonlinear(host: Host, capacity: float, n: int) -> float:
32     """ Non-linear resource sharing for CPU """
33     # emulates a degradation in CPU according to the number of tasks
34     # totally unrealistic but for learning purposes
35     capacity = capacity / 2 if n > 1 else capacity
36     this_actor.info("Host %s, %d concurrent tasks, new capacity %f" %
37                     (host.name, n, capacity))
38     return capacity
39
40
41 def load_platform():
42     """ Create a simple 1-host platform """
43     zone = NetZone.create_empty_zone("Zone1")
44     runner_host = zone.create_host("runner", 1e6)
45     runner_host.set_sharing_policy(
46         Host.SharingPolicy.NONLINEAR, functools.partial(cpu_nonlinear, runner_host))
47     runner_host.seal()
48     zone.seal()
49
50     # create actor runner
51     Actor.create("runner", runner_host, runner)
52
53
54 if __name__ == '__main__':
55     e = Engine(sys.argv)
56
57     # create platform
58     load_platform()
59
60     # runs the simulation
61     e.run()
62
63     # explicitly deleting Engine object to avoid segfault during cleanup phase.
64     # During Engine destruction, the cleanup of std::function linked to non_linear callback is called.
65     # If we let the cleanup by itself, it fails trying on its destruction because the python main program
66     # has already freed its variables
67     del(e)