FlashGraph-ng
A new frontier in large-scale graph analysis and data mining
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Pages
compute_stat.h
1 #ifndef __COMPUTE_STAT_H__
2 #define __COMPUTE_STAT_H__
3 
4 /*
5  * Copyright 2014 Open Connectome Project (http://openconnecto.me)
6  * Written by Da Zheng (zhengda1936@gmail.com)
7  *
8  * This file is part of SAFSlib.
9  *
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  *
14  * http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  */
22 
23 #include "concurrency.h"
24 
25 /*
26  * These provides a thread-safe way to compute some statistics:
27  * mean, max, min, etc on streaming data.
28  */
29 
30 /*
31  * Compute the average value of elements in a vector.
32  */
33 template<class T>
34 class stat_mean
35 {
36  atomic_number<T> tot;
37  atomic_number<T> num;
38 public:
39  void add(T v) {
40  tot.inc(v);
41  num.inc(1);
42  }
43 
44  double get() const {
45  return ((double) tot.get()) / num.get();
46  }
47 };
48 
49 template<class T>
50 class stat_max
51 {
52  atomic_number<T> max;
53 public:
54  void add(T v) {
55  while (true) {
56  T orig_max = max.get();
57  // The original max is smaller, try to switch to the new max.
58  if (orig_max < v) {
59  bool ret = max.CAS(orig_max, v);
60  // If we succeed, we can stop now.
61  if (ret)
62  break;
63  // Otherwise, we need to try again.
64  }
65  else
66  // The original max is larger, we just stop the loop and
67  // do nothing.
68  break;
69  }
70  }
71 
72  T get() const {
73  return max.get();
74  }
75 };
76 
77 #endif