计算的嵌套for循环的执行时间

问题描述 投票:0回答:1

假设我有一个嵌套for循环,并且如果-检查如下所示,如果我想了解有多少个时钟周期(最终多少秒)的特定的for循环,或者如果检查正在执行完毕。

应时钟周期(秒)的数量之和采取的内部for循环,并且如果检查被相等(或大致相等)的时钟周期(秒)的数量所采取的最外部for循环。?

还是我做错了?我如何一次循环,如果有做的任何其他方式?

注:我有3个不同的功能做几乎同样的事情,我已经宣布3个不同的功能来衡量每个for循环或分开,如果检查“因为如果我试图让所有的子组件的执行时间在同一块的代码,然后由外for循环取时钟周期(秒)的数量将包括这些计算的时钟周期计数的内部的for循环,并且如果检查我想说明一些额外的执行。

void fun1(){
       int i=0,j=0,k=0;
    clock_t t=0,t_start=0,t_end=0;
    //time the outermost forloop
    t_start = clock();
    for(i=0;i<100000;i++){
            for(j=0;j<1000;j++){
                    //some code
                    }
            if(k==0){
              //some code
                 }
            }
    t_end = clock();
    t=t_end-t_start;
    double time_taken = ((double)t)/CLOCKS_PER_SEC;
    printf("outer for-loop took %f seconds to execute \n", time_taken);
 }

void fun2(){
    int i=0,j=0,k=0;
    clock_t t2=0,t2_start=0,t2_end=0;
    for(i=0;i<100000;i++){
            //time the inner for loop
            t2_start=clock();
            for(j=0;j<1000;j++){
                    //some code
                    }
            t2_end=clock();
            t2+=(t2_end-t2_start);

            if(k==0){
                 //some code
                     }
            }
    double time_taken = ((double)t2)/CLOCKS_PER_SEC;
    printf("inner for-loop took %f seconds to execute \n", time_taken);
  }

 void fun3(){
    int i=0,j=0,k=0;
    clock_t t3=0,t3_start=0,t3_end=0;
    for(i=0;i<100000;i++){
            for(j=0;j<1000;j++){
                 //some code
                       }
            //time the if check
            t3_start=clock();
            if(k==0){
                    //some code
                    }
            t3_end=clock();
            t3+=(t3_end-t3_start);
            }
    double time_taken = ((double)t3)/CLOCKS_PER_SEC;
    printf("if-check took %f seconds to execute \n", time_taken);
  }
c
1个回答
0
投票

预期的答案是tfun1可能会比t2+t3稍微从fun2fun3分别代表了更多的时间来评估外环本身。

不太明显,但是,是通过测量本身,这将是调用clock()本身一次为每个测量时加入的时间。当测量内部循环,它有效地乘以100,000,因为外循环的迭代。

这里的测量测量本身的程序,并有很好的措施,也测量评估空外环的时间。

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

int main () {
    clock_t t = 0;
    clock_t t_start, t_end;

    for (int i = 0; i < 100000; i++) {
        t_start = clock();
        t_end = clock();
        t += (t_end - t_start);
    }
    double time_taken = ((double) t) / CLOCKS_PER_SEC;
    printf ("Time imposed by measurement itself: %fsec\n", time_taken);


    t_start = clock();
    for (int i = 0; i < 100000; i++) {
    }
    t_end = clock();
    t = (t_end - t_start);
    time_taken = ((double) t) / CLOCKS_PER_SEC;
    printf ("Time to evaluate the loop: %fsec\n", time_taken);
}

其中,至少在我的系统上,建议测量可能会扭曲的结果会:

Time imposed by measurement itself: 0.056949sec
Time to evaluate the loop: 0.000200sec

要获取时间的内部循环“真的”走量,你需要减去的是通过测量它的行为增加。

© www.soinside.com 2019 - 2024. All rights reserved.