小编Nai*_*ekh的帖子

如何以微秒为单位衡量执行时间?

我编写了以下代码来测量对任何数据进行排序的时间。我得到的结果很奇怪,例如在某些情况下为负时间,并且对于相同的数据集没有得到任何一致的结果(我知道这不会完全相同)。请让我知道哪里出了问题或如何正确测量时间。

#include<stdio.h>
#include<sys/time.h>

void bubble(int a[],int n)
{
    int i,j,flag,temp;
    for(i=0;i<n-1;i++)
    {
        flag=0;
        for(j=0;j<n-i-1;j++)
        {
            if(a[j]>a[j+1])
            {
                flag=1;
                a[j]=a[j]+a[j+1];
                a[j+1]=a[j]-a[j+1];
                a[j]=a[j]-a[j+1];
            }
        }
        if(flag==0)
            break;
    }
}

int main()
{
    int n,a[100000],i;
    printf("Enter the size of array:");
    scanf("%d",&n);
    for(i=0;i<n;i++)
        a[i]=rand()%100000;     //average case
        //a[i]=i;               //best case
        //a[i]=n-1-i;           //worst case
    /*
    printf("The UNsorted array is:\n");
    for(i=0;i<n;i++)
        printf("%d ",a[i]);
    printf("\n\n");
    */

    int st,et;
    struct timezone tz;
    struct timeval tv;
    gettimeofday(&tv,NULL);
    st=tv.tv_usec;
    bubble(a,n);
    gettimeofday(&tv,NULL);
    et=tv.tv_usec;
    printf("Sorting time: %d micro seconds\n",et-st);
    /*
    printf("\nThe sorted array …
Run Code Online (Sandbox Code Playgroud)

c execution-time

5
推荐指数
1
解决办法
7062
查看次数

标签 统计

c ×1

execution-time ×1