編寫程序肯定要使用計時功能,來判斷程序的執行時間。今天Google了一下,自己就梳理總結一下:
(1)C/C++程序計時
C/C++中使用的計時函數是clock()。
C語言中的頭文件對應是#include<time.h>,C++中對應的頭文件為#include<ctime>。
如下程序實例,其中clock_t為long類型,CLOCKS_PER_SEC為每秒的時鍾周期常數:
1 #include<iostream> 2 #include <ctime> 3 using namespace std; 4 5 int test() 6 { 7 int x=0; 8 for(int i=0;i<200000000;i++) 9 x=(i/5); 10 return 0; 11 } 12 int main() 13 { 14 clock_t start,end; 15 start=clock(); //開始時間 16 test(); 17 end=clock(); //結束時間 18 19 cout<<"執行時間(秒):"<<(double)(end-start)/CLOCKS_PER_SEC<<endl; 20 getchar(); 21 return 0; 22 }
執行結果:
(2)Java程序計時
Java中使用Calendar類獲取系統當前時間來進行執行時間的判斷。
如下程序實例:
1 import java.util.Calendar; 2 3 public class TimerCal { 4 static int test(){ 5 int x; 6 for(int i=0;i<200000000;i++) 7 x=i/5; 8 return 0; 9 } 10 11 public static void main(String[] args){ 12 long start=Calendar.getInstance().getTimeInMillis(); 13 test(); 14 long end=Calendar.getInstance().getTimeInMillis(); 15 System.out.println("執行時間(秒):"+(double)(end-start)/1000); 16 } 17 }
執行結果: