linux
#include <sys/time.h> #include <iostream> #include <time.h> double get_wall_time() { struct timeval time ; if (gettimeofday(&time,NULL)){ return 0; } return (double)time.tv_sec + (double)time.tv_usec * .000001; } int main() { unsigned int t = 0; double start_time = get_wall_time(); while(t++ < 10e+6); double end_time = get_wall_time() ; std::cout<<"循环耗时为:"<<end_time-start_time<<"ms"; return 0; }
windows
#include <windows.h> #include <iostream> int main() { DWORD start, stop; unsigned int t = 0; start = GetTickCount(); while (t++ < 10e+6); stop = GetTickCount(); printf("time: %lld ms\n", stop - start); return 0; }
本文提供了一个在Linux和Windows平台上测量循环耗时的示例代码。通过使用特定于平台的API,如Linux的gettimeofday和Windows的GetTickCount,来精确测量代码执行时间。这有助于开发者理解和优化不同操作系统上的程序性能。
1101

被折叠的 条评论
为什么被折叠?



