summaryrefslogtreecommitdiff
path: root/graphics/asymptote/profiler.h
blob: bd914d55d1224cdf2d4f7231f920722adb13e766 (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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
/*****
 * profiler.h
 * Andy Hammerlindl 2010/07/24
 *
 * Profiler for the execution of the virtual machine bytecode.
 *****/

#ifndef PROFILER_H
#define PROFILER_H

#include <sys/time.h>

#include <iostream>

#include "inst.h"

namespace vm {

#ifdef DEBUG_BLTIN
string lookupBltin(bltin b);
#endif

inline position positionFromLambda(lambda *func) {
  if (func == 0)
    return position();

  program& code = *func->code;

  // Check for empty program.
  if (code.begin() == code.end())
    return position();

  return code.begin()->pos;
}

inline void printNameFromLambda(ostream& out, lambda *func) {
  if (!func) {
    out << "<top level>";
    return;
  }
  
#ifdef DEBUG_FRAME
  string name = func->name;
#else
  string name = "";
#endif

  // If unnamed, use the pointer address.
  if (name.empty())
    out << func;
  else
    out << name;

  out << " at ";
  positionFromLambda(func).printTerse(out);
}

inline void printNameFromBltin(ostream& out, bltin b) {
#ifdef DEBUG_BLTIN
  string name = lookupBltin(b);
#else
  string name = "";
#endif

  if (!name.empty())
    out << name << " ";
  out << "(builtin at " << (void *)b << ")";
}

class profiler : public gc {
  // To do call graph analysis, each call stack that occurs in practice is
  // represented by a node.  For instance, if f and g are functions, then
  //   f -> g -> g
  // is represented by a node and
  //   g -> f -> g
  // is represented by a different one.
  struct node {
    // The top-level function of the call stack.  It is either an asymptote
    // function with a given lambda, or a builtin function, with a given
    // bltin.
    lambda *func;
    bltin cfunc;

    // The number of times the top-level function has been called resulting in
    // this specific call stack.
    int calls;

    // The number of bytecode instructions executed with this exact call stack.
    // It does not include time spent in called function.
    int instructions;

    // Number of instructions spent in this function or its children.  This is
    // computed by computeTotals.
    int instTotal;

    // The number of real-time nanoseconds spent in this node.  WARNING: May
    // be wildly inaccurate.
    long long nsecs;

    // Total including children.
    long long nsecsTotal;

    // Call stacks resulting from calls during this call stack.
    mem::vector<node> children;

    node()
      : func(0), cfunc(0), calls(0),
        instructions(0), instTotal(0),
        nsecs(0), nsecsTotal(0) {}

    node(lambda *func)
      : func(func), cfunc(0), calls(0),
        instructions(0), instTotal(0),
        nsecs(0), nsecsTotal(0) {}

    node(bltin b)
      : func(0), cfunc(b), calls(0),
        instructions(0), instTotal(0),
        nsecs(0), nsecsTotal(0) {}

    // Return the call stack resulting from a call to func when this call
    // stack is current.
    node *getChild(lambda *func) {
      size_t n = children.size();
      for (size_t i = 0; i < n; ++i)
        if (children[i].func == func)
          return &children[i];

      // Not found, create a new one.
      children.push_back(node(func));
      return &children.back();
    }
    node *getChild(bltin func) {
      size_t n = children.size();
      for (size_t i = 0; i < n; ++i)
        if (children[i].cfunc == func)
          return &children[i];

      // Not found, create a new one.
      children.push_back(node(func));
      return &children.back();
    }

    void computeTotals() {
      instTotal = instructions;
      nsecsTotal = nsecs;
      size_t n = children.size();
      for (size_t i = 0; i < n; ++i) {
        children[i].computeTotals();
        instTotal += children[i].instTotal;
        nsecsTotal += children[i].nsecsTotal;
      }
    }



    void pydump(ostream& out) {
#ifdef DEBUG_FRAME
      string name = func ? func->name : "<top level>";
#else
      string name = "";
#endif

      out << "dict(\n"
           << "    name = '" << name << " " << func << "',\n"
           << "    pos = '" << positionFromLambda(func) << "',\n"
           << "    calls = " << calls << ",\n"
           << "    instructions = " << instructions << ",\n"
           << "    nsecs = " << nsecs << ",\n"
           << "    children = [\n";

      size_t n = children.size();
      for (size_t i = 0; i < n; ++i) {
        children[i].pydump(out);
        out << ",\n";
      }

      out << "    ])\n";
    }
  };

  // An empty call stack.
  node emptynode;

  // All of the callstacks.
  std::stack<node *> callstack;

  node &topnode() {
    return *callstack.top();
  }

  // Arc representing one function calling another.  Used only for building
  // the output for kcachegrind.
  struct arc : public gc {
    int calls;
    int instTotal;
    long long nsecsTotal;

    arc() : calls(0), instTotal(0), nsecsTotal(0) {}

    void add(node& n) {
      calls += n.calls;
      instTotal += n.instTotal;
      nsecsTotal += n.nsecsTotal;
    }
  };

  // Representing one function and its calls to other functions.
  struct fun : public gc {
    int instructions;
    long long nsecs;
    mem::map<lambda *, arc> arcs;
    mem::map<bltin, arc> carcs;

    fun() : instructions(0), nsecs(0) {}

    void addChildTime(node& n) {
      if (n.cfunc)
        carcs[n.cfunc].add(n);
      else
        arcs[n.func].add(n);
    }

    void analyse(node& n) {
      instructions += n.instructions;
      nsecs += n.nsecs;
      size_t numChildren = n.children.size();
      for (size_t i = 0; i < numChildren; ++i)
        addChildTime(n.children[i]);
    }

    void dump(ostream& out) {
      // The unused line number needed by kcachegrind.
      static const string POS = "1";

      out << POS << " " << instructions << " " << nsecs << "\n";
      for (mem::map<lambda *, arc>::iterator i = arcs.begin();
           i != arcs.end();
           ++i)
      {
        lambda *l = i->first;
        arc& a = i->second;

        out << "cfl=" << positionFromLambda(l) << "\n";

        out << "cfn=";
        printNameFromLambda(out, l);
        out << "\n";

        out << "calls=" << a.calls << " " << POS << "\n";
        out << POS << " " << a.instTotal << " " << a.nsecsTotal << "\n";
      }
      for (mem::map<bltin, arc>::iterator i = carcs.begin();
           i != carcs.end();
           ++i)
      {
        bltin b = i->first;
        arc& a = i->second;

        out << "cfl=C++ code" << endl;

        out << "cfn=";
        printNameFromBltin(out, b);
        out << "\n";

        out << "calls=" << a.calls << " " << POS << "\n";
        out << POS << " " << a.instTotal << " " << a.nsecsTotal << "\n";
      }
    }
  };

  // The data for each asymptote function.
  mem::map<lambda *, fun> funs;

  // The data for each C++ function.
  mem::map<bltin, fun> cfuns;

  void analyseNode(node& n) {
    fun& f = n.cfunc ? cfuns[n.cfunc] :
                       funs[n.func];

    f.analyse(n);

    size_t numChildren = n.children.size();
    for (size_t i = 0; i < numChildren; ++i)
      analyseNode(n.children[i]);
  }

  // Convert data in the tree of callstack nodes into data for each function.
  void analyseData() {
    emptynode.computeTotals();
    analyseNode(emptynode);
  }


  // Timing data.
  struct timeval timestamp;

  void startLap() {
    gettimeofday(&timestamp, 0);
  }

  long long timeAndResetLap() {
    struct timeval now;
    gettimeofday(&now, 0);
    long long nsecs = 1000000000LL * (now.tv_sec - timestamp.tv_sec) +
                      1000LL * (now.tv_usec - timestamp.tv_usec);
    timestamp = now;
    return nsecs;
  }

  // Called whenever the stack is about to change, in order to record the time
  // duration for the current node.
  void recordTime() {
    topnode().nsecs += timeAndResetLap();
  }

public:
  profiler();

  void beginFunction(lambda *func);
  void endFunction(lambda *func);
  void beginFunction(bltin func);
  void endFunction(bltin func);
  void recordInstruction();

  // TODO: Add position, type of instruction info to profiling.

  // Dump all of the data out in a format that can be read into Python.
  void pydump(ostream &out);

  // Dump all of the data in a format for kcachegrind.
  void dump(ostream& out);

};

inline profiler::profiler()
  : emptynode()
{
    callstack.push(&emptynode);
    startLap();
}

inline void profiler::beginFunction(lambda *func) {
  assert(func);
  assert(!callstack.empty());

  recordTime();

  callstack.push(topnode().getChild(func));
  ++topnode().calls;
}

inline void profiler::endFunction(lambda *func) {
  assert(func);
  assert(!callstack.empty());
  assert(topnode().func == func);

  recordTime();

  callstack.pop();
}

inline void profiler::beginFunction(bltin cfunc) {
  assert(cfunc);
  assert(!callstack.empty());

  recordTime();

  callstack.push(topnode().getChild(cfunc));
  ++topnode().calls;
}

inline void profiler::endFunction(bltin cfunc) {
  assert(cfunc);
  assert(!callstack.empty());
  assert(topnode().cfunc == cfunc);

  recordTime();

  callstack.pop();
}

inline void profiler::recordInstruction() {
  assert(!callstack.empty());
  ++topnode().instructions;
}

inline void profiler::pydump(ostream& out) {
  out << "profile = ";
  emptynode.pydump(out);
}

inline void profiler::dump(ostream& out) {
  analyseData();

  out << "events: Instructions Nanoseconds\n";

  for (mem::map<lambda *, fun>::iterator i = funs.begin();
       i != funs.end();
       ++i)
  {
    lambda *l = i->first;
    fun& f = i->second;

    out << "fl=" << positionFromLambda(l) << "\n";

    out << "fn=";
    printNameFromLambda(out, l);
    out << "\n";

    f.dump(out);
  }
  for (mem::map<bltin, fun>::iterator i = cfuns.begin();
       i != cfuns.end();
       ++i)
  {
    bltin b = i->first;
    fun& f = i->second;

    out << "fl=C++ code\n";

    out << "fn=";
    printNameFromBltin(out, b);
    out << "\n";

    f.dump(out);
  }
}


} // namespace vm

#endif // PROFILER_H