Apache SINGA
A distributed deep learning platform .
 All Classes Namespaces Files Functions Variables Typedefs Enumerator Macros
common.h
1 #ifndef INCLUDE_UTILS_COMMON_H_
2 #define INCLUDE_UTILS_COMMON_H_
3 #pragma once
4 #include <glog/logging.h>
5 #include <gflags/gflags.h>
6 #include <google/protobuf/message.h>
7 #include <stdarg.h>
8 #include <string>
9 #include <vector>
10 #include <sstream>
11 #include <sys/stat.h>
12 #include <map>
13 
14 using std::vector;
15 using std::string;
16 using std::map;
17 using google::protobuf::Message;
18 
19 #ifndef GFLAGS_GFLAGS_H_
20 namespace gflags = google;
21 #endif // GFLAGS_GFLAGS_H_
22 
23 
24 namespace singa {
25 
26 void ReadProtoFromTextFile(const char* filename, Message* proto) ;
27 void WriteProtoToTextFile(const Message& proto, const char* filename) ;
28 void ReadProtoFromBinaryFile(const char* filename, Message* proto) ;
29 void WriteProtoToBinaryFile(const Message& proto, const char* filename);
30 
31 std::string IntVecToString(const vector<int>& vec) ;
32 string StringPrintf(string fmt, ...) ;
33 void Debug() ;
34 inline bool check_exists(const std::string& name) {
35  struct stat buffer;
36  return (stat (name.c_str(), &buffer) == 0);
37 }
38 
39 /*
40 inline void Sleep(int millisec=1){
41  std::this_thread::sleep_for(std::chrono::milliseconds(millisec));
42 }
43 */
44 
45 inline float rand_real(){
46  return static_cast<float>(rand())/(RAND_MAX+1.0f);
47 }
48 
49 class Metric{
50  public:
51  Metric():counter_(0){}
52  void AddMetric(const string& name, float value){
53  string prefix=name;
54  if(name.find("@")!=string::npos)
55  prefix=name.substr(0, name.find("@"));
56  if(data_.find(prefix)==data_.end())
57  data_[prefix]=value;
58  else
59  data_[prefix]+=value;
60  }
61  void AddMetrics(const Metric& other){
62  for(auto& entry: other.data_)
63  AddMetric(entry.first, entry.second);
64  }
65  void Reset(){
66  data_.clear();
67  counter_=0;
68  }
69  void Avg(){
70  for(auto& entry: data_)
71  entry.second/=counter_;
72  }
73  void Inc(){
74  counter_++;
75  }
76  const string ToString() const{
77  string disp=std::to_string(data_.size())+" fields, ";
78  for(const auto& entry: data_){
79  disp+=entry.first+" : "+std::to_string(entry.second)+"\t";
80  }
81  return disp;
82  }
83  void ParseString(const string & perf) {
84  std::stringstream stream(perf);
85  int n;
86  string str;
87  stream>>n>>str;
88  for(int i=0;i<n;i++){
89  float f;
90  string sep;
91  stream>>str>>sep>>f;
92  data_[str]=f;
93  }
94  }
95  private:
96  map<string, float> data_;
97  int counter_;
98 };
99 } /* singa */
100 #endif // INCLUDE_UTILS_COMMON_H_
Definition: common.h:49