]> git.cworth.org Git - fips/blob - metrics.c
0c61e0ebab1620e715b4dad64c825c86452dade5
[fips] / metrics.c
1 /* Copyright © 2013, Intel Corporation
2  *
3  * Permission is hereby granted, free of charge, to any person obtaining a copy
4  * of this software and associated documentation files (the "Software"), to deal
5  * in the Software without restriction, including without limitation the rights
6  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7  * copies of the Software, and to permit persons to whom the Software is
8  * furnished to do so, subject to the following conditions:
9  *
10  * The above copyright notice and this permission notice shall be included in
11  * all copies or substantial portions of the Software.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19  * THE SOFTWARE.
20  */
21
22 #define _GNU_SOURCE
23
24 #include <inttypes.h>
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <assert.h>
29 #include <time.h>
30 #include <sys/time.h>
31 #include <string.h>
32 #include <errno.h>
33
34 #include "fips-dispatch-gl.h"
35
36 #include "metrics.h"
37 #include "context.h"
38 #include "metrics-info.h"
39 #include "xmalloc.h"
40
41 int frames;
42 int verbose;
43
44 #define MAX_MONITORS_IN_FLIGHT 1000
45
46 /* Timer query */
47 typedef struct timer_query
48 {
49         unsigned id;
50
51         metrics_op_t op;
52         struct timer_query *next;
53 } timer_query_t;
54
55 /* Performance-monitor query */
56 typedef struct monitor
57 {
58         unsigned id;
59
60         metrics_op_t op;
61         struct monitor *next;
62 } monitor_t;
63
64 typedef struct op_metrics
65 {
66         /* This happens to also be the index into the
67          * metrics->op_metrics array currently
68          */
69         metrics_op_t op;
70         double time_ns;
71
72         double **counters;
73 } op_metrics_t;
74
75 struct metrics
76 {
77         /* Description of all available peformance counters, counter
78          * groups, their names and IDs, etc. */
79         metrics_info_t *info;
80
81         /* The current operation being measured. */
82         metrics_op_t op;
83
84         /* GL_TIME_ELAPSED query for which glEndQuery has not yet
85          * been called. */
86         unsigned timer_begun_id;
87
88         /* GL_TIME_ELAPSED queries for which glEndQuery has been
89          * called, (but results have not yet been queried). */
90         timer_query_t *timer_head;
91         timer_query_t *timer_tail;
92
93         /* Performance monitor for which glEndPerfMonitorAMD has not
94          * yet been called. */
95         unsigned monitor_begun_id;
96
97         /* Performance monitors for which glEndPerfMonitorAMD has
98          * been called, (but results have not yet been queried). */
99         monitor_t *monitor_head;
100         monitor_t *monitor_tail;
101
102         int monitors_in_flight;
103
104         unsigned num_op_metrics;
105         op_metrics_t *op_metrics;
106
107         /* Per-frame time and latency measurement. */
108         GLint64 swap_begin_timestamp;
109         unsigned swap_end_timestamp_id;
110         GLint64 previous_swap_end_timestamp;
111
112         struct timespec previous_cpu_time_ts;
113         struct timespec cpu_time_ts;
114 };
115
116 metrics_t *
117 metrics_create (metrics_info_t *info)
118 {
119         metrics_t *metrics;
120
121         metrics = xmalloc (sizeof (metrics_t));
122
123         metrics->info = info;
124
125         metrics->op = 0;
126
127         metrics->timer_begun_id = 0;
128
129         metrics->timer_head = NULL;
130         metrics->timer_tail = NULL;
131
132         metrics->monitor_begun_id = 0;
133
134         metrics->monitor_head = NULL;
135         metrics->monitor_tail = NULL;
136
137         metrics->monitors_in_flight = 0;
138
139         metrics->num_op_metrics = 0;
140         metrics->op_metrics = NULL;
141
142         glGenQueries (1, &metrics->swap_end_timestamp_id);
143
144         /* Get the first frame timestamp started immediately. */
145         glQueryCounter (metrics->swap_end_timestamp_id, GL_TIMESTAMP);
146
147         return metrics;
148 }
149
150 void
151 metrics_fini (metrics_t *metrics)
152 {
153         timer_query_t *timer, *timer_next;
154         monitor_t *monitor, *monitor_next;
155
156         /* Discard and cleanup any outstanding queries. */
157         if (metrics->timer_begun_id) {
158                 glEndQuery (GL_TIME_ELAPSED);
159                 glDeleteQueries (1, &metrics->timer_begun_id);
160                 metrics->timer_begun_id = 0;
161         }
162
163         for (timer = metrics->timer_head;
164              timer;
165              timer = timer_next)
166         {
167                 glDeleteQueries (1, &timer->id);
168                 timer_next = timer->next;
169                 free (timer);
170         }
171         metrics->timer_head = NULL;
172         metrics->timer_tail = NULL;
173
174         if (metrics->info->have_perfmon) {
175
176                 if (metrics->monitor_begun_id) {
177                         glEndPerfMonitorAMD (metrics->monitor_begun_id);
178                         glDeletePerfMonitorsAMD (1, &metrics->monitor_begun_id);
179                         metrics->monitor_begun_id = 0;
180                 }
181
182                 for (monitor = metrics->monitor_head;
183                      monitor;
184                      monitor = monitor_next)
185                 {
186                         glDeletePerfMonitorsAMD (1, &monitor->id);
187                         monitor_next = monitor->next;
188                         free (monitor);
189                 }
190                 metrics->monitor_head = NULL;
191                 metrics->monitor_tail = NULL;
192
193         }
194
195         metrics->monitors_in_flight = 0;
196 }
197
198 void
199 metrics_destroy (metrics_t *metrics)
200 {
201         metrics_fini (metrics);
202
203         free (metrics);
204 }
205
206 static const char *
207 metrics_op_string (metrics_op_t op)
208 {
209         if (op >= METRICS_OP_SHADER)
210                 return "Shader program";
211
212         switch (op)
213         {
214         case METRICS_OP_ACCUM:
215                 return "glAccum*(+)";
216         case METRICS_OP_BUFFER_DATA:
217                 return "glBufferData(+)";
218         case METRICS_OP_BUFFER_SUB_DATA:
219                 return "glCopyBufferSubData*";
220         case METRICS_OP_BITMAP:
221                 return "glBitmap*";
222         case METRICS_OP_BLIT_FRAMEBUFFER:
223                 return "glBlitFramebuffer*";
224         case METRICS_OP_CLEAR:
225                 return "glClear(+)";
226         case METRICS_OP_CLEAR_BUFFER_DATA:
227                 return "glCearBufferData(+)";
228         case METRICS_OP_CLEAR_TEX_IMAGE:
229                 return "glClearTexImage(+)";
230         case METRICS_OP_COPY_PIXELS:
231                 return "glCopyPixels";
232         case METRICS_OP_COPY_TEX_IMAGE:
233                 return "glCopyTexImage(+)";
234         case METRICS_OP_DRAW_PIXELS:
235                 return "glDrawPixels";
236         case METRICS_OP_GET_TEX_IMAGE:
237                 return "glGetTexImage(+)";
238         case METRICS_OP_READ_PIXELS:
239                 return "glReadPixels*";
240         case METRICS_OP_TEX_IMAGE:
241                 return "glTexImage*(+)";
242         default:
243                 fprintf (stderr, "fips: Internal error: "
244                          "Unknown metrics op value: %d\n", op);
245                 exit (1);
246         }
247
248         return "";
249 }
250
251 void
252 metrics_counter_start (metrics_t *metrics)
253 {
254         unsigned i;
255
256         /* Initialize the timer_query object. */
257         glGenQueries (1, &metrics->timer_begun_id);
258
259         /* Most everything else in this function is
260          * performance-monitor related. If we don't have that
261          * extension, just start the timer query and be done. */
262         if (! metrics->info->have_perfmon) {
263                 glBeginQuery (GL_TIME_ELAPSED, metrics->timer_begun_id);
264                 return;
265         }
266
267         /* Initialize the performance-monitor object */
268         glGenPerfMonitorsAMD (1, &metrics->monitor_begun_id);
269
270         for (i = 0; i < metrics->info->num_groups; i++)
271         {
272                 metrics_group_info_t *group;
273                 int num_counters;
274
275                 group = &metrics->info->groups[i];
276
277                 num_counters = group->num_counters;
278                 if (group->max_active_counters < group->num_counters)
279                 {
280                         fprintf (stderr, "Warning: Only monitoring %d/%d counters from group %d\n",
281                                  group->max_active_counters,
282                                  group->num_counters, i);
283                         num_counters = group->max_active_counters;
284
285                 }
286
287                 glSelectPerfMonitorCountersAMD(metrics->monitor_begun_id,
288                                                GL_TRUE, group->id,
289                                                num_counters,
290                                                group->counter_ids);
291         }
292
293         /* Start the queries */
294         glBeginQuery (GL_TIME_ELAPSED, metrics->timer_begun_id);
295
296         glBeginPerfMonitorAMD (metrics->monitor_begun_id);
297 }
298
299 void
300 metrics_counter_stop (metrics_t *metrics)
301 {
302         timer_query_t *timer;
303         monitor_t *monitor;
304
305         /* Stop the current timer and monitor. */
306         glEndQuery (GL_TIME_ELAPSED);
307
308         if (metrics->info->have_perfmon)
309                 glEndPerfMonitorAMD (metrics->monitor_begun_id);
310
311         /* Add these IDs to our lists of outstanding queries and
312          * monitors so the results can be collected later. */
313         timer = xmalloc (sizeof (timer_query_t));
314
315         timer->op = metrics->op;
316         timer->id = metrics->timer_begun_id;
317         timer->next = NULL;
318
319         if (metrics->timer_tail) {
320                 metrics->timer_tail->next = timer;
321                 metrics->timer_tail = timer;
322         } else {
323                 metrics->timer_tail = timer;
324                 metrics->timer_head = timer;
325         }
326
327         if (metrics->info->have_perfmon) {
328                 /* Create a new performance-monitor query */
329                 monitor = xmalloc (sizeof (monitor_t));
330
331                 monitor->op = metrics->op;
332                 monitor->id = metrics->monitor_begun_id;
333                 monitor->next = NULL;
334
335                 if (metrics->monitor_tail) {
336                         metrics->monitor_tail->next = monitor;
337                         metrics->monitor_tail = monitor;
338                 } else {
339                         metrics->monitor_tail = monitor;
340                         metrics->monitor_head = monitor;
341                 }
342         }
343
344         metrics->monitors_in_flight++;
345
346         /* Avoid being a resource hog and collect outstanding results
347          * once we have sent off a large number of
348          * queries. (Presumably, many of the outstanding queries are
349          * available by now.)
350          */
351         if (metrics->monitors_in_flight > MAX_MONITORS_IN_FLIGHT)
352                 metrics_collect_available (metrics);
353 }
354
355 void
356 metrics_set_current_op (metrics_t *metrics, metrics_op_t op)
357 {
358         metrics->op = op;
359 }
360
361 metrics_op_t
362 metrics_get_current_op (metrics_t *metrics)
363 {
364         return metrics->op;
365 }
366
367 static void
368 op_metrics_init (metrics_info_t *info, op_metrics_t *metrics, metrics_op_t op)
369 {
370         unsigned i, j;
371
372         metrics->op = op;
373         metrics->time_ns = 0.0;
374
375         metrics->counters = xmalloc (sizeof(double *) * info->num_groups);
376
377         for (i = 0; i < info->num_groups; i++) {
378                 metrics->counters[i] = xmalloc (sizeof (double) *
379                                                 info->groups[i].num_counters);
380                 for (j = 0; j < info->groups[i].num_counters; j++)
381                         metrics->counters[i][j] = 0.0;
382         }
383 }
384
385 static op_metrics_t *
386 _get_op_metrics (metrics_t *metrics, metrics_op_t op)
387 {
388         unsigned i;
389
390         if (op >= metrics->num_op_metrics)
391         {
392                 metrics->op_metrics = realloc (metrics->op_metrics,
393                                                (op + 1) * sizeof (op_metrics_t));
394                 for (i = metrics->num_op_metrics; i < op + 1; i++)
395                         op_metrics_init (metrics->info, &metrics->op_metrics[i], i);
396
397                 metrics->num_op_metrics = op + 1;
398         }
399
400         return &metrics->op_metrics[op];
401 }
402
403 static void
404 accumulate_program_metrics (metrics_t *metrics, metrics_op_t op,
405                             GLuint *result, GLuint size)
406 {
407 #define CONSUME(var)                                                    \
408         if (p + sizeof(var) > ((unsigned char *) result) + size)        \
409         {                                                               \
410                 fprintf (stderr, "Unexpected end-of-buffer while "      \
411                          "parsing results\n");                          \
412                 break;                                                  \
413         }                                                               \
414         (var) = *((typeof(var) *) p);                                   \
415         p += sizeof(var);
416
417         metrics_info_t *info = metrics->info;
418         op_metrics_t *op_metrics = _get_op_metrics (metrics, op);
419         unsigned char *p = (unsigned char *) result;
420
421         while (p < ((unsigned char *) result) + size)
422         {
423                 GLuint group_id, group_index;
424                 GLuint counter_id, counter_index;
425                 metrics_group_info_t *group;
426                 double value;
427                 unsigned i;
428
429                 CONSUME (group_id);
430                 CONSUME (counter_id);
431
432                 for (i = 0; i < info->num_groups; i++) {
433                         if (info->groups[i].id == group_id)
434                                 break;
435                 }
436                 group_index = i;
437                 assert (group_index < info->num_groups);
438                 group = &info->groups[group_index];
439
440                 for (i = 0; i < group->num_counters; i++) {
441                         if (group->counter_ids[i] == counter_id)
442                                 break;
443                 }
444                 counter_index = i;
445                 assert (counter_index < group->num_counters);
446
447                 switch (group->counter_types[counter_index])
448                 {
449                         uint uint_value;
450                         uint64_t uint64_value;
451                         float float_value;
452                 case GL_UNSIGNED_INT:
453                         CONSUME (uint_value);
454                         value = uint_value;
455                         break;
456                 case GL_UNSIGNED_INT64_AMD:
457                         CONSUME (uint64_value);
458                         value = uint64_value;
459                         break;
460                 case GL_PERCENTAGE_AMD:
461                 case GL_FLOAT:
462                         CONSUME (float_value);
463                         value = float_value;
464                         break;
465                 default:
466                         fprintf (stderr, "fips: Warning: Unknown counter value type (%d)\n",
467                                  group->counter_types[counter_index]);
468                         value = 0.0;
469                         break;
470                 }
471
472                 op_metrics->counters[group_index][counter_index] += value;
473         }
474 }
475
476 static void
477 accumulate_program_time (metrics_t *metrics, metrics_op_t op, unsigned time_ns)
478 {
479         op_metrics_t *op_metrics;
480
481         op_metrics = _get_op_metrics (metrics, op);
482
483         op_metrics->time_ns += time_ns;
484 }
485
486 typedef struct per_stage_metrics
487 {
488         op_metrics_t *metrics;
489         shader_stage_info_t *stage;
490         double time_ns;
491         double active;
492 } per_stage_metrics_t;
493
494 static int
495 _is_shader_stage_counter (metrics_info_t *info,
496                           unsigned group_index,
497                           unsigned counter_index)
498 {
499         shader_stage_info_t *stage;
500         unsigned i;
501
502         for (i = 0; i < info->num_shader_stages; i++) {
503                 stage = &info->stages[i];
504
505                 if (stage->active_group_index == group_index &&
506                     stage->active_counter_index == counter_index)
507                 {
508                         return 1;
509                 }
510
511                 if (stage->stall_group_index == group_index &&
512                     stage->stall_counter_index == counter_index)
513                 {
514                         return 1;
515                 }
516         }
517
518         return 0;
519 }
520
521 static void
522 print_per_stage_metrics (metrics_t *metrics,
523                          per_stage_metrics_t *per_stage,
524                          double total)
525 {
526         metrics_info_t *info = metrics->info;
527         op_metrics_t *op_metrics = per_stage->metrics;
528         metrics_group_info_t *group;
529         const char *op_string;
530         unsigned group_index, counter;
531         double value;
532
533         /* Don't print anything for stages with no alloted time. */
534         if (per_stage->time_ns == 0.0)
535                 return;
536
537         op_string = metrics_op_string (op_metrics->op);
538
539         printf ("%21s", op_string);
540
541         if (op_metrics->op >= METRICS_OP_SHADER) {
542                 printf (" %3d", op_metrics->op - METRICS_OP_SHADER);
543         } else {
544                 printf ("    ");
545
546         }
547
548         if (per_stage->stage)
549                 printf (" %cS:", per_stage->stage->name[0]);
550         else
551                 printf ("   :");
552
553         printf ("\t%7.2f ms (%4.1f%%)",
554                 per_stage->time_ns / 1e6,
555                 per_stage->time_ns / total * 100);
556
557         if (per_stage->active)
558                 printf (", %4.1f%% active", per_stage->active * 100);
559
560         printf ("\n");
561
562         /* I'm not seeing a lot of value printing the rest of these
563          * performance counters by default yet. Use --verbose to get
564          * them for now. */
565         if (! verbose)
566                 return;
567
568         printf ("[");
569         for (group_index = 0; group_index < info->num_groups; group_index++) {
570                 group = &info->groups[group_index];
571                 for (counter = 0; counter < group->num_counters; counter++) {
572
573                         /* Don't print this counter value if it's a
574                          * per-stage cycle counter, (which we have
575                          * already accounted for). */
576                         if (_is_shader_stage_counter (info, group_index, counter))
577                                 continue;
578
579                         value = op_metrics->counters[group_index][counter];
580                         if (value == 0.0)
581                                 continue;
582                         printf ("%s: %.2f ", group->counter_names[counter],
583                                 value / 1e6);
584                 }
585         }
586         printf ("]\n");
587 }
588
589 static int
590 time_compare(const void *in_a, const void *in_b, void *arg unused)
591 {
592         const per_stage_metrics_t *a = in_a;
593         const per_stage_metrics_t *b = in_b;
594
595
596         if (a->time_ns < b->time_ns)
597                 return -1;
598         if (a->time_ns > b->time_ns)
599                 return 1;
600         return 0;
601 }
602
603 static void
604 print_program_metrics (metrics_t *metrics)
605 {
606         metrics_info_t *info = metrics->info;
607         unsigned num_shader_stages = info->num_shader_stages;
608         per_stage_metrics_t *sorted, *per_stage;
609         double total_time, op_cycles;
610         op_metrics_t *op;
611         unsigned group_index, counter_index;
612         unsigned i, j, num_sorted;
613
614         if (! info->have_perfmon &&
615             ! info->printed_missing_perfmon_warning)
616         {
617                 fprintf (stderr,
618                          "Warning: The GL_AMD_performance_monitor extensions is not available.\n"
619                          "         Some fips features, (such as per-shader-stage timings),\n"
620                          "         will not be available.\n");
621
622                 info->printed_missing_perfmon_warning = true;
623         }
624
625         /* Make a sorted list of the per-stage operations by time
626          * used, and figure out the total so we can print percentages.
627          */
628         if (num_shader_stages)
629                 num_sorted = metrics->num_op_metrics * num_shader_stages;
630         else
631                 num_sorted = metrics->num_op_metrics;
632
633         sorted = xmalloc (sizeof (*sorted) * num_sorted);
634
635         total_time = 0.0;
636
637         for (i = 0; i < metrics->num_op_metrics; i++) {
638
639                 op = &metrics->op_metrics[i];
640
641                 /* Accumulate total time across all ops. */
642                 total_time += op->time_ns;
643
644                 /* Also, find total cycles in all stages of this op. */
645                 op_cycles = 0.0;
646
647                 if (num_shader_stages == 0) {
648                         per_stage = &sorted[i];
649                         per_stage->metrics = op;
650                         per_stage->stage = NULL;
651                         per_stage->time_ns = op->time_ns;
652                         per_stage->active = 0.0;
653                 }
654
655                 for (j = 0; j < num_shader_stages; j++) {
656                         /* Active cycles */
657                         group_index = info->stages[j].active_group_index;
658                         counter_index = info->stages[j].active_counter_index;
659                         op_cycles += op->counters[group_index][counter_index];
660
661                         /* Stall cycles */
662                         group_index = info->stages[j].stall_group_index;
663                         counter_index = info->stages[j].stall_counter_index;
664                         op_cycles += op->counters[group_index][counter_index];
665                 }
666
667                 for (j = 0; j < num_shader_stages; j++) {
668                         double active_cycles, stall_cycles, stage_cycles;
669
670                         /* Active cycles */
671                         group_index = info->stages[j].active_group_index;
672                         counter_index = info->stages[j].active_counter_index;
673                         active_cycles = op->counters[group_index][counter_index];
674
675                         /* Stall cycles */
676                         group_index = info->stages[j].stall_group_index;
677                         counter_index = info->stages[j].stall_counter_index;
678                         stall_cycles = op->counters[group_index][counter_index];
679
680                         stage_cycles = active_cycles + stall_cycles;
681
682                         per_stage = &sorted[i * num_shader_stages + j];
683                         per_stage->metrics = op;
684
685                         if (op_cycles) {
686                                 per_stage->stage = &info->stages[j];
687                                 per_stage->time_ns = op->time_ns * (stage_cycles / op_cycles);
688                         } else {
689                                 /* If we don't have any per-stage cycle counts
690                                  * for this operation, then use the first
691                                  * stage as a placeholder for all the time,
692                                  * but NULL-ify the stage info so that the
693                                  * report doesn't lie about this time being
694                                  * from any particular stage. */
695                                 per_stage->stage = NULL;
696                                 if (j == 0) {
697                                         per_stage->time_ns = op->time_ns;
698                                 } else {
699                                         per_stage->time_ns = 0.0;
700                                 }
701                         }
702
703                         if (stage_cycles) {
704                                 per_stage->active = active_cycles / stage_cycles;
705                         } else {
706                                 per_stage->active = 0.0;
707                         }
708                 }
709         }
710
711         qsort_r (sorted, num_sorted, sizeof (*sorted),
712                  time_compare, metrics->op_metrics);
713
714         for (i = 0; i < num_sorted; i++)
715                 print_per_stage_metrics (metrics, &sorted[i], total_time);
716
717         free (sorted);
718 }
719
720 void
721 metrics_collect_available (metrics_t *metrics)
722 {
723         /* Consume all timer queries that are ready. */
724         timer_query_t *timer = metrics->timer_head;
725
726         while (timer) {
727                 GLuint available, elapsed;
728
729                 glGetQueryObjectuiv (timer->id,
730                                      GL_QUERY_RESULT_AVAILABLE, &available);
731                 if (! available)
732                         break;
733
734                 glGetQueryObjectuiv (timer->id,
735                                      GL_QUERY_RESULT, &elapsed);
736
737                 accumulate_program_time (metrics, timer->op, elapsed);
738
739                 metrics->timer_head = timer->next;
740                 if (metrics->timer_head == NULL)
741                         metrics->timer_tail = NULL;
742
743                 glDeleteQueries (1, &timer->id);
744
745                 free (timer);
746                 timer = metrics->timer_head;
747         }
748
749         if (! metrics->info->have_perfmon)
750                 return;
751
752         /* And similarly for all performance monitors that are ready. */
753         monitor_t *monitor = metrics->monitor_head;
754
755         while (monitor) {
756                 GLuint available, result_size, *result;
757                 GLint bytes_written;
758
759                 glGetPerfMonitorCounterDataAMD (monitor->id,
760                                                 GL_PERFMON_RESULT_AVAILABLE_AMD,
761                                                 sizeof (available), &available,
762                                                 NULL);
763                 if (! available)
764                         break;
765
766                 glGetPerfMonitorCounterDataAMD (monitor->id,
767                                                 GL_PERFMON_RESULT_SIZE_AMD,
768                                                 sizeof (result_size),
769                                                 &result_size, NULL);
770
771                 result = xmalloc (result_size);
772
773                 glGetPerfMonitorCounterDataAMD (monitor->id,
774                                                 GL_PERFMON_RESULT_AMD,
775                                                 result_size, result,
776                                                 &bytes_written);
777
778                 accumulate_program_metrics (metrics, monitor->op, result, result_size);
779
780                 free (result);
781
782                 metrics->monitor_head = monitor->next;
783                 if (metrics->monitor_head == NULL)
784                         metrics->monitor_tail = NULL;
785
786                 glDeletePerfMonitorsAMD (1, &monitor->id);
787
788                 free (monitor);
789
790                 metrics->monitors_in_flight--;
791
792                 monitor = metrics->monitor_head;
793         }
794 }
795
796 /* Return the difference from ts0 to ts1 as floating-point seconds. */
797 #define TIMESPEC_DIFF(ts0, ts1) (double) (ts1.tv_sec - ts0.tv_sec + \
798                                           (ts1.tv_nsec - ts0.tv_nsec) / 1e9)
799
800 void
801 metrics_end_frame_pre_swap (metrics_t *metrics)
802 {
803         GLuint64 swap_end_timestamp, frame_time_ns, latency_ns;
804         double cpu_time;
805
806         /* Don't leave any counters running over the end_frame work we
807          * do here. The counters will be started again at the end of
808          * metrics_end_frame_post_swap.  */
809
810         metrics_counter_stop (metrics);
811
812         /* Now that an entire frame's worth of content has gone by, we
813          * can be sure that the timer quiery for the previous frame's
814          * swap is available.
815          *
816          * Note: The only case in which this query isn't immediately
817          * available would be if there was effectively nothing in this
818          * frame. In that case, triggering a block on this query
819          * result is not a concern (since an empty frame is not
820          * interesting, and all of our counters are stopped anyway).
821          *
822          * Accepting this one block is much better than adding a
823          * linked list for these results that would reaslisticly never
824          * have more than one entry anyway.
825          */
826
827         glGetQueryObjectui64v (metrics->swap_end_timestamp_id,
828                                GL_QUERY_RESULT, &swap_end_timestamp);
829
830         if (frames == 0) {
831                 /* Print header */
832                 printf ("# frame: Frame_Number Frame_Time_milliseconds Frame_latency_milliseconds CPU_load\n");
833         } else {
834                 /* Subtract previous frame's times to get frame times. */
835                 frame_time_ns = swap_end_timestamp - metrics->previous_swap_end_timestamp;
836
837                 latency_ns = swap_end_timestamp - metrics->swap_begin_timestamp;
838
839                 cpu_time = TIMESPEC_DIFF (metrics->previous_cpu_time_ts, metrics->cpu_time_ts);
840
841                 /* We've waited one frame to ensure we have a timestamp
842                  * result. So the time we've actually measured here is
843                  * for the previous frame. */
844                 printf ("frame: %d %g %g %g\n",
845                         frames - 1,
846                         (double) frame_time_ns / 1e6,
847                         (double) latency_ns / 1e6,
848                         cpu_time / (frame_time_ns / 1e9));
849         }
850
851         metrics->previous_swap_end_timestamp = swap_end_timestamp;
852         metrics->previous_cpu_time_ts = metrics->cpu_time_ts;
853
854         /* Before the actual swap call, we get the current timestamp
855          * value. This is a synchronous get so we can use this as the
856          * baseline for a frame latency measurment. */
857
858         glGetInteger64v (GL_TIMESTAMP, &metrics->swap_begin_timestamp);
859 }
860
861 void
862 metrics_end_frame_post_swap (metrics_t *metrics)
863 {
864         static int initialized = 0;
865         static struct timeval tv_start, tv_now;
866         int err;
867
868         /* Now that the swap command has been queued, we issue an
869          * asynchronous query of the timestamp value. Comparing this
870          * to the synchronous get we just sent in
871          * metrics_end_frame_pre_swap allows us to measure the
872          * per-frame swap latency. */
873
874         glQueryCounter (metrics->swap_end_timestamp_id, GL_TIMESTAMP);
875
876         /* Query the total amount of CPU time spent by this process. */
877         err = clock_gettime (CLOCK_PROCESS_CPUTIME_ID, &metrics->cpu_time_ts);
878         if (err == -1 ) {
879                 fprintf (stderr, "Failed to query CPU time with clock_gettime: %s\n",
880                          strerror (errno));
881                 exit (1);
882         }
883
884         if (! initialized) {
885                 gettimeofday (&tv_start, NULL);
886                 if (getenv ("FIPS_VERBOSE"))
887                         verbose = 1;
888                 initialized = 1;
889         }
890
891         metrics_collect_available (metrics);
892
893         frames++;
894
895         if (frames % 15 == 0) {
896                 double fps;
897
898                 gettimeofday (&tv_now, NULL);
899
900                 fps = (double) frames / (tv_now.tv_sec - tv_start.tv_sec +
901                                          (tv_now.tv_usec - tv_start.tv_usec) / 1.0e6);
902
903                 printf("FPS: %.3f\n", fps);
904
905                 print_program_metrics (metrics);
906         }
907
908         /* Start the counter up again now that we're done. */
909         metrics_counter_start (metrics);
910 }