1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # Extension to inject memory-tracing instrumentation in code generated by `nitc`.
18 import abstract_compiler
20 redef class ToolContext
22 var opt_trace_memory
= new OptionBool("Enable dynamic measure of memory usage", "--trace-memory")
25 self.option_context
.add_option opt_trace_memory
29 redef class AbstractCompiler
30 redef fun compile_before_main
(v
)
34 if not modelbuilder
.toolcontext
.opt_trace_memory
.value
then return
36 header
.add_decl
("#include <time.h>")
37 header
.add_decl
("extern FILE *mlog;")
38 header
.add_decl
("extern struct timespec mlog_last;")
39 header
.add_decl
("extern struct timespec mlog_time0;")
40 v
.add_decl
("FILE *mlog;")
41 v
.add_decl
("struct timespec mlog_last;")
42 v
.add_decl
("struct timespec mlog_time0;")
45 redef fun compile_begin_main
(v
)
49 if not modelbuilder
.toolcontext
.opt_trace_memory
.value
then return
51 v
.add
("mlog = fopen(\"memory
.log\
", \"w\
");")
52 v
.add
("clock_gettime(CLOCK_MONOTONIC, &mlog_time0);")
56 redef class AbstractCompilerVisitor
57 redef fun nit_alloc
(size
, tag
)
59 if not compiler
.modelbuilder
.toolcontext
.opt_trace_memory
.value
then return super
61 # Log time each 10ms (ie 1e7ns)
62 var tw
= get_name
("mtw")
63 add_decl
("struct timespec {tw};")
64 add
("clock_gettime(CLOCK_MONOTONIC, &{tw});")
65 add
("if(mlog_last.tv_sec < {tw}.tv_sec || mlog_last.tv_nsec + 1e7 < {tw}.tv_nsec) \{")
66 add
("mlog_last = {tw};")
67 add
("fprintf(mlog, \"# %f\\n\", 1000.0*{tw}.tv_sec + 1e-6*{tw}.tv_nsec - (1000.0*mlog_time0.tv_sec + 1e-6*mlog_time0.tv_nsec));")
70 # Print size and tag the mlog
71 var str
= "\"+\\t
%d\\t
%s\\n\
", {size}, \"{tag or else "?"}\
""
72 add
("fprintf(mlog, {str});")