4、caffe.cpp之命令解析

    xiaoxiao2021-04-18  52

    主函数位置:caffe/tool/caffe.cpp (主要以train阶段阅读的代码),下面是从主函数代码抽象出的主干代码(稍加修改).主要以代码阅读进行学习;

    #include <gflags/gflags.h> #include <glog/logging.h> #include <cstring> #include <map> #include <string> #include <vector> #include<iostream> using namespace std; // A simple registry for caffe commands. typedef int (*BrewFunction)(); typedef map< string, BrewFunction> BrewMap; BrewMap g_brew_map; #define RegisterBrewFunction(func) \ namespace { \ class __Registerer_##func { \ public: /* NOLINT */ \ __Registerer_##func() { \ g_brew_map[#func] = &func; \ } \ }; \ __Registerer_##func g_registerer_##func; \ } static BrewFunction GetBrewFunction(const string& name) { if (g_brew_map.count(name)) { return g_brew_map[name]; } else { LOG(ERROR) << "Available caffe actions:"; for (BrewMap::iterator it = g_brew_map.begin(); it != g_brew_map.end(); ++it) { LOG(ERROR) << "\t" << it->first; } LOG(FATAL) << "Unknown action: " << name; return NULL; // not reachable, just to suppress old compiler warnings. } } // Train / Finetune a model. int train() { LOG(INFO) << "Train phase."; return 0; } RegisterBrewFunction(train); // Test: score a model. int test() { LOG(INFO) << "Test phase."; return 0; } RegisterBrewFunction(test); // Time: benchmark the execution time of a model. int time() { LOG(INFO) << "Time"; return 0; } RegisterBrewFunction(time); int main(int argc, char** argv) { FLAGS_alsologtostderr = 1; google::InitGoogleLogging(argv[0]); GetBrewFunction( argv[1])(); return 0; }

    代码的编译及运行为:

    g++ test.cpp -o test -lglog -lgflags -lpthread ubuntu@ubuntu:~$ ./test train I0620 15:37:08.277657 9474 d.cpp:42] Train phase. ubuntu@ubuntu:~$ ./test test I0620 15:37:13.148831 9475 d.cpp:49] Test phase.

    -lglog 是日志log变量的编译参数 -lgflags -lpthread -l 链接库进行编译,针对gflag 这是最基本的命令框架解析caffe中的命令行解析代码.

    自己仿照写了一个小demo;之前还见过get_opt处理参数;有机会在写demo

    #include<iostream> #include<map> #include<cstring> using namespace std; //宏在执行之前,已经完成A类的无参数构造函数初始化 #define registerFun(fun) class A##fun { public: A##fun() { mapStrFun[#fun]=&fun; } }; A##fun a##fun; typedef int (*fun)(); //回调函数 typedef map<string,fun> Map; Map mapStrFun; static fun function(const string &name) { if(name.size()!=0)z return mapStrFun[name]; else return NULL; } int train() { cout<<"enter train phase"<<endl; return 0; } registerFun(train); int test() { cout<<"enter test phase"<<endl; return 0; } registerFun(test); int main(int argc, char** argv) { function(argv[1])(); return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-674806.html

    最新回复(0)