c语言获取系统时间跨平台方法及计算程序运行时间

void getCurrentDateTime(char* current_datetime)
{
    time_t nowtime;
    struct tm* timeinfo;
    time(&nowtime);
    timeinfo = localtime(&nowtime);
    int xtn = timeinfo->tm_year + 1900;
    xtn = xtn % 2000;
    int xty = timeinfo->tm_mon + 1;
    int xtr = timeinfo->tm_mday;
    int xts = timeinfo->tm_hour;
    int xtf = timeinfo->tm_min;
    int xtm = timeinfo->tm_sec;
    snprintf(current_datetime, 18, "%d-%d-%d %d:%d:%d", xtn, xty, xtr, xts, xtf, xtm);
}

char* current_datetime = malloc(18);
memset(current_datetime, 0, 18);
getCurrentDateTime(current_datetime);

计算程序的耗时

#include <sys/time.h>
int main(int argc, char** argv)
{
struct timeval start, stop, diff; gettimeofday(&start, 0); //开始计时 for (int i=0;i<100000;i++) { root = json_tokener_parse(json_str); // 每次20us changes = json_object_object_get(root, "change"); } gettimeofday(&stop, 0); //结束计时 timeval_subtract(&diff, &start, &stop); printf("总计用时:%d秒%d微秒\n",diff.tv_sec, diff.tv_usec); }
int timeval_subtract(struct timeval* result, struct timeval* x, struct timeval* y) { if (x->tv_sec > y->tv_sec) return -1; if ((x->tv_sec == y->tv_sec) && (x->tv_usec > y->tv_usec)) return -1; result->tv_sec = (y->tv_sec - x->tv_sec); result->tv_usec = (y->tv_usec - x->tv_usec); if (result->tv_usec < 0) { result->tv_sec--; result->tv_usec += 1000000; } return 0; }

 头文件time.h和sys/time.h的区别与关系https://blog.csdn.net/holabin/article/details/105613741

posted @ 2022-05-11 11:21  zhjh256  阅读(184)  评论(0编辑  收藏  举报