1// Copyright (c) 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include <sys/time.h>
6
7// Timer helper for fps.  Returns seconds elapsed since first call to
8// getseconds(), as a double.
9static inline double getseconds() {
10  static int first_call = 1;
11  static struct timeval start_tv;
12  static int start_tv_retv;
13  const double usec_to_sec = 0.000001;
14
15  if (first_call) {
16    first_call = 0;
17    start_tv_retv = gettimeofday(&start_tv, NULL);
18  }
19
20  struct timeval tv;
21  if ((0 == start_tv_retv) && (0 == gettimeofday(&tv, NULL)))
22    return (tv.tv_sec - start_tv.tv_sec) + tv.tv_usec * usec_to_sec;
23  return 0.0;
24}
25
26struct FpsState {
27  double last_time;
28  int frame_count;
29};
30
31/**
32 * Initialize the FpsState object.
33 */
34inline void FpsInit(struct FpsState* state) {
35  state->last_time = getseconds();
36  state->frame_count = 0;
37}
38
39/**
40 * Call this whenever you render, after calling FpsInit above.
41 *
42 * Returns 1 if the value should be displayed. In this case, the result will
43 * be written to the |out_fps| parameter.
44 */
45inline int FpsStep(struct FpsState* state, double* out_fps) {
46  const double kFpsUpdateSecs = 1.0f;
47  double current_time = getseconds();
48
49  state->frame_count++;
50
51  if (current_time < state->last_time + kFpsUpdateSecs)
52    return 0;
53
54  *out_fps = state->frame_count / (current_time - state->last_time);
55  state->last_time = current_time;
56  state->frame_count = 0;
57  return 1;
58}
59