[cpp]%20view%20plain%20copy%20<span style="font-size:14px;"><span style="font-size:18px;">#include<iostream> #include<time.h> using namespace std; int main() { clock_t startTime,endTime; startTime = clock(); for (int i = 0; i < 1000000; i++) { i++; } endTime = clock(); cout << "Totle Time : " <<(double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl; system("pause"); return 0; }</span></span> [cpp]%20view%20plain%20copy%20<span style="font-size:14px;">#include<iostream> #include<time.h> using namespace std; int main() { for (int i = 0; i < 1000000; i++) { i++; } cout << "Totle Time : " << (double)clock() /CLOCKS_PER_SEC<< "s" << endl; system("pause"); return 0; }</span>
方法二:GetTickCount()函数:
GetTickCount是函数。GetTickCount返回(retrieve)从操作系统启动所经过(elapsed)的毫秒数,它的返回值是DWord。函数原型:DWORD%20GetTickCount(void);头文件:C/C++头文件:winbase.hwindows程序设计中可以使用头文件windows.h测试代码:[cpp]%20view%20plain%20copy%20<span style="font-size:14px;">#include<iostream> #include<Windows.h> using namespace std; int main() { DWORD start_time = GetTickCount(); for (int i = 0; i < 100000000; i++) { i++; } DWORD end_time = GetTickCount(); cout << "The run time is:" << (end_time - start_time) << "ms!" << endl; system("pause"); return 0; }</span> 注意事项:GetTickcount函数:它返回从操作系统启动到当前所经过的毫秒数,常常用来判断某个方法执行的时间,其函数原型是DWORD GetTickCount(void),返回值以32位的双字类型DWORD存储,因此可以存储的最大值是(2^32-1) ms约为49.71天,因此若系统运行时间超过49.71天时,这个数就会归0,MSDN中也明确的提到了:"Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days."。因此,如果是编写服务器端程序,此处一定要万分注意,避免引起意外的状况。特别注意:这个函数并非实时发送,而是由系统每18ms发送一次,因此其最小精度为18ms。当需要有小于18ms的精度计算时,应使用StopWatch方法进行。用clock()函数计算运行时间,表示范围一定大于GetTickCount()函数,所以,建议使用clock()函数。