C/C++/Java 程序计时功能函数

编写程序肯定要使用计时功能,来判断程序的执行时间。今天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 }

执行结果:

posted on 2013-12-07 14:18  旭东的博客  阅读(3992)  评论(0编辑  收藏  举报

导航