summaryrefslogtreecommitdiffstats
path: root/src/common/DecayCounter.cc
blob: bdc750112ad98abcff0f9a2b2a0576641b1f4fce (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
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

#include "DecayCounter.h"
#include "Formatter.h"

#include "include/encoding.h"

void DecayCounter::encode(bufferlist& bl) const
{
  decay();
  ENCODE_START(5, 4, bl);
  encode(val, bl);
  ENCODE_FINISH(bl);
}

void DecayCounter::decode(bufferlist::const_iterator &p)
{
  DECODE_START_LEGACY_COMPAT_LEN(5, 4, 4, p);
  if (struct_v < 2) {
    double k = 0.0;
    decode(k, p);
  }
  if (struct_v < 3) {
    double k = 0.0;
    decode(k, p);
  }
  decode(val, p);
  if (struct_v < 5) {
    double delta, _;
    decode(delta, p);
    val += delta;
    decode(_, p); /* velocity */
  }
  last_decay = clock::now();
  DECODE_FINISH(p);
}

void DecayCounter::dump(Formatter *f) const
{
  decay();
  f->dump_float("value", val);
  f->dump_float("halflife", rate.get_halflife());
}

void DecayCounter::generate_test_instances(std::list<DecayCounter*>& ls)
{
  DecayCounter *counter = new DecayCounter();
  counter->val = 3.0;
  counter->rate = DecayRate(2.0);
  ls.push_back(counter);
  counter = new DecayCounter();
  ls.push_back(counter);
}

void DecayCounter::decay(double delta) const
{
  auto now = clock::now();
  double el = std::chrono::duration<double>(now - last_decay).count();

  // calculate new value
  double newval = val * exp(el * rate.k) + delta;
  if (newval < .01) {
    newval = 0.0;
  }

  val = newval;
  last_decay = now;
}