测试程序运行时间的三种方法

来源:互联网 发布:php b2b开源系统 编辑:程序博客网 时间:2024/06/05 09:59

第一种方法

#include <sys/time.h>

#if 0
int gettimeofday(struct timeval *tv,struct timezone *tz);
strut timeval {
    long tv_sec; /* 秒数 */
    long tv_usec; /* 微秒数 */
};
gettimeofday将时间保存在结构tv之中.tz一般我们使用NULL来代替.
#endif
#include <sys/time.h>
#include <stdio.h>
#include <math.h>
void function()
{
    unsigned int i,j;
    double y;
    for(i=0;i<1000;i++)
        for(j=0;j<1000;j++)
            y=sin((double)i);
}
main()
{
    struct timeval tpstart,tpend;
    float timeuse;
    gettimeofday(&tpstart,NULL);
    function();
    gettimeofday(&tpend,NULL);
    timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+
        tpend.tv_usec-tpstart.tv_usec;
    timeuse/=1000000;
    printf("Used Time:%fn",timeuse);
    exit(0);

}


第二种方法

#include <stdio.h>
#include <time.h>
//ÄãÒª²âÊԵĎúÂëÔÚÕâÀï
int main(){
    int i,j;
    clock_t start,end,time;
    //GetTickCount(void);
    start = clock();
    for(i=0;i<10000;i++)
        for(j=0;j<100;j++)
            ;
    //GetTickCount(void);
    end = clock();
    time = end -start;
    printf("time = %f\n",time);
    return 0;
}


第三种方法

#include<stdio.h>
#include<time.h>
//#include <Windows.h>
#include <sys/types.h>
/*
¿ìËÙÅÅÐòËã·šµÄÁœžöÖ÷Òª²œÖ裬·Öžî£šPartitionºÍQuickSort£©
*/
int Partition(int a[],int low,int high);
void QuickSort(int a[],int low,int high);
void main()
{
    int i ;
    double start,end,time;
    start=GetTickCount();
    int a[9]={8,2,3,4,5,6,76,0,334};
    QuickSort(a,0,8);
    for(i=0;i<9;i++)
        printf("%d ",a[i]);
    end=GetTickCount();
    time=end-start;
    printf("%d", time) ;
    // return 0;
}
 
int Partition(int a[],int low,int high)
{
    int key=a[low];
 
    while(low<high)
    {
        while(low<high&&a[high]>=key) high--;
        a[low]=a[high];
        while(low<high&&a[low]<=key) low++;
        a[high]=a[low];
    }
    return low;
}
 
void QuickSort(int a[],int low,int high)
{
    if(low<high)
    {
        int p=Partition(a,low,high);
        QuickSort(a,p+1,high);
        QuickSort(a,low, p-1);
    }
}




原创粉丝点击