C++時間格式化輸出,延時秒毫秒(sleep,msleep)

#include <string>

using namespace std;

//defin common date-time format string
static const char* fmt_def[7] = {
    "[%Y-%m-%d %H:%M:%S]",  //[2016-12-12 14:30:20]
    "[%Y/%m/%d %H:%M:%S]",  //[2016-12-12 14:30:20]
    "%Y-%m-%d %H:%M:%S",    //2016-12-12 14:30:20
    "%Y/%m/%d %H:%M:%S",    //2016/12/12 14:30:20
    "%Y-%m-%d",             //2016-12-12
    "%Y/%m/%d",             //2016/12/12
    "%H:%M:%S"              //14:30:20
};

//format date-time to string
string fmt_date_time(const char* fmt);

//this thread sleep milliseconds
void msleep(unsigned long msecs);

//this thread sleep seconds
void sleep(unsigned long secs);

//CPP
////////////////////////////////////////////////
#include <thread>
//#include <chrono>
//#include <ctime>

string fmt_date_time(const char* fmt)
{
    time_t rawtime;
    time(&rawtime);
    struct tm * timeinfo = localtime (&rawtime);
    char buffer[256] = {0};
    strftime (buffer, 256, fmt, timeinfo);
    return string(buffer);
}

void msleep(unsigned long msecs)
{
    //clock_t now = clock();
    //while ((clock()-now)<msecs);

    //C++11 support
    std::this_thread::sleep_for(std::chrono::milliseconds(msecs));
}

void sleep(unsigned long secs)
{
//    time_t start = time(nullptr);
//    time_t stop = start;
//    while (difftime(stop, start) < secs) {
//        stop = time(nullptr);
//    }

    //C++11 support
    std::this_thread::sleep_for(std::chrono::seconds(secs));
}
相關文章
相關標籤/搜索