对时间按指定时间段进行分组,可用于并发度计算
#include <iostream> #include <string> #include <sstream> #include <vector> using namespace std; unsigned long long strToull(const string & a_str) { #if defined (WIN32) return strtoul(a_str.c_str(), NULL, 10); #else return strtoull(a_str.c_str(), NULL, 10); #endif } vector<string> getGroupList(int a_iGroup, const string &a_strStartTime, const string &a_strEndTime) { time_t tStartTime = strToull(a_strStartTime.c_str()); time_t tEndTime = strToull(a_strEndTime.c_str()); //cout<<"begin "<<tStartTime<<" end "<<tEndTime<<endl; struct tm tmNow; tm* pTm = localtime_r(&tStartTime, &tmNow); struct tm *tmNew = new tm(); *tmNew = *pTm; tmNew->tm_min = int(pTm->tm_min/a_iGroup) * a_iGroup; tmNew->tm_sec = 0; char tmBuf[64]; memset(tmBuf, 0, sizeof(tmBuf)); strftime(tmBuf, 64, "%Y-%m-%d %H:%M:00", tmNew); stringstream str; str<<a_iGroup<<"-"<<tmBuf; vector<string> valuelist; valuelist.push_back(str.str()); time_t tBegin = mktime(tmNew) + a_iGroup * 60; while(tBegin < tEndTime) { struct tm tmTime; localtime_r(&tBegin, &tmTime); memset(tmBuf, 0, sizeof(tmBuf)); strftime(tmBuf, 64, "%Y-%m-%d %H:%M:00", &tmTime); stringstream strs; strs<<a_iGroup<<"-"<<tmBuf; valuelist.push_back(strs.str()); tBegin += a_iGroup * 60; } return valuelist; } int main(int argc, char* argv[]) { int group = 1; if(argc == 2) { group = atoi(argv[1]); } else { cout<<"help:"<<endl; cout<<" ./get group"<<endl; return 0; } vector<string> valuelist = getGroupList(group, "1472111395", "1472112495"); for(vector<string>::iterator iter = valuelist.begin(); iter != valuelist.end(); ++iter) { cout<<"value is:"<<*iter<<endl; } return 0; }
g++ getgrouplist.cpp -o get
输出: