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
分类:
c/c++/go/rust
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!