aboutsummaryrefslogtreecommitdiff
path: root/extras/benchmark/fruit_source_generator.py
blob: 5346aeaa30d5f22b481cab0fd0325b3ca5f315cb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


def generate_files(injection_graph, generate_runtime_bench_code):
    file_content_by_name = dict()

    for node_id in injection_graph.nodes_iter():
        file_content_by_name['component%s.h' % node_id] = _generate_component_header(node_id)
        file_content_by_name['component%s.cpp' % node_id] = _generate_component_source(node_id, injection_graph.successors(node_id))

    [toplevel_node] = [node_id
                       for node_id in injection_graph.nodes_iter()
                       if not injection_graph.predecessors(node_id)]
    file_content_by_name['main.cpp'] = _generate_main(toplevel_node, generate_runtime_bench_code)

    return file_content_by_name

def _get_component_type(component_index):
    return 'fruit::Component<Interface{component_index}>'.format(**locals())

def _generate_component_header(component_index):
    component_type = _get_component_type(component_index)
    template = """
#ifndef COMPONENT{component_index}_H
#define COMPONENT{component_index}_H

#include <fruit/fruit.h>

// Example include that the code might use
#include <vector>

struct Interface{component_index} {{
  virtual ~Interface{component_index}() = default;
}};

{component_type} getComponent{component_index}();

#endif // COMPONENT{component_index}_H
"""
    return template.format(**locals())

def _generate_component_source(component_index, deps):
    include_directives = ''.join(['#include "component%s.h"\n' % index for index in deps + [component_index]])

    fields = ''.join(['Interface%s& x%s;\n' % (dep, dep)
                      for dep in deps])

    component_deps = ', '.join(['Interface%s& x%s' % (dep, dep)
                                for dep in deps])
    param_initializers = ', '.join('x%s(x%s)' % (dep, dep)
                                   for dep in deps)
    if param_initializers:
        param_initializers = ': ' + param_initializers

    install_expressions = ''.join(['        .install(getComponent%s)\n' % dep for dep in deps])

    component_type = _get_component_type(component_index)

    template = """
{include_directives}

namespace {{
struct X{component_index} : public Interface{component_index} {{
  {fields}

  INJECT(X{component_index}({component_deps})) {param_initializers} {{}}

  virtual ~X{component_index}() = default;
}};
}}

"""

    template += """
{component_type} getComponent{component_index}() {{
    return fruit::createComponent(){install_expressions}
        .bind<Interface{component_index}, X{component_index}>();
}}
"""

    return template.format(**locals())

def _generate_main(toplevel_component, generate_runtime_bench_code):
    if generate_runtime_bench_code:
        template = """
#include "component{toplevel_component}.h"

#include <ctime>
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <chrono>

using namespace std;

fruit::Component<> getEmptyComponent() {{
  return fruit::createComponent();
}}

int main(int argc, char* argv[]) {{
  if (argc != 2) {{
    std::cout << "Need to specify num_loops as argument." << std::endl;
    exit(1);
  }}
  size_t num_loops = std::atoi(argv[1]);
  
  std::chrono::high_resolution_clock::time_point start_time = std::chrono::high_resolution_clock::now();
  for (size_t i = 0; i < 1 + num_loops/100; i++) {{
    fruit::NormalizedComponent<Interface{toplevel_component}> normalizedComponent(getComponent{toplevel_component});
    (void)normalizedComponent;
  }}
  double componentNormalizationTime = std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - start_time).count();

  start_time = std::chrono::high_resolution_clock::now();
  for (size_t i = 0; i < 1 + num_loops/100; i++) {{
    fruit::Injector<Interface{toplevel_component}> injector(getComponent{toplevel_component});
    injector.get<std::shared_ptr<Interface{toplevel_component}>>();
  }}
  double fullInjectionTime = std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - start_time).count();  

  fruit::NormalizedComponent<Interface{toplevel_component}> normalizedComponent(getComponent{toplevel_component});
    
  start_time = std::chrono::high_resolution_clock::now();
  for (size_t i = 0; i < num_loops; i++) {{
    fruit::Injector<Interface{toplevel_component}> injector(normalizedComponent, getEmptyComponent);
    injector.get<std::shared_ptr<Interface{toplevel_component}>>();
  }}
  double perRequestTime = std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - start_time).count();

  std::cout << std::fixed;
  std::cout << std::setprecision(15);
  std::cout << "componentNormalizationTime = " << componentNormalizationTime * 100 / num_loops << std::endl;
  std::cout << "Total for setup            = " << componentNormalizationTime * 100 / num_loops << std::endl;
  std::cout << "Full injection time        = " << fullInjectionTime * 100 / num_loops << std::endl;
  std::cout << "Total per request          = " << perRequestTime / num_loops << std::endl;
  return 0;
}}
    """
    else:
        template = """
#include "component{toplevel_component}.h"

int main(void) {{
  fruit::Injector<Interface{toplevel_component}> injector(getComponent{toplevel_component});
  injector.get<std::shared_ptr<Interface{toplevel_component}>>();
  return 0;
}}
    """

    return template.format(**locals())