本文介绍了在C语言循环中获取特定代码部分的时序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面,我有一个程序正在执行两个简单的加法和乘法运算.然后,我将这两个简单运算的总和存储在两个分别称为total1和total2的变量中.在计算方面,total2将花费更多时间才能完全执行.我实现代码的方式,目前正在对两种数学运算的整个模拟进行计时.

Below I have a program that is performing two simple addition and multiplication operations. I am then storing the sum of these two simple operations in two respective variables called total1 and total2. In terms of computation total2 will take more time to be fully executed. The way I implemented the code, I am currently timing the entire simulation of both mathematical operations.

是否可以分别对合计1和合计2的最终结果计时?我要求如此,因为我希望以单独的方式获取total1和total2的具体时间.

Is it possible to time solely the end result of total1 and total 2 separately? I am asking so as I wish to get the specific time of total1 and total2 in a separate manner.

我完全意识到,长久占用内存是昂贵的,而且不是节省内存的最有效方法.此代码和问题的唯一目的是计时,而不是代码优化.

I am fully aware that long long is expensive with regards to memory and is not the most efficient way to save up memory. The sole purpose of this code and question is timing and not code optimization.

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

int main()
{

     long long total1 = 0, total2 = 0, i = 0;
     double simulation_time = 0;

     clock_t Start = clock();

     do
     {
          total1 += i + i;
          total2 += i * i * i * i;

          i++;

     } while (i < 1000000000);

     clock_t End = clock();

     printf("Total 1 = %u \n", total1);
     printf("Total 2 = %u \n", total2);

     simulation_time = (double)(End - Start) / CLOCKS_PER_SEC;
     printf("Runtime of Whole Simulation using clock_t: %f\n", simulation_time);


     return 0;
}

推荐答案

我不确定我是否理解您的问题,但是要分别计时每个操作,您只需要进行两个单独的循环即可.

I am not sure I understand your problem, but to time each operation separately you simply have to make two separate loops.

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

int main()
{
    long long total1 = 0, total2 = 0, i = 0, j = 1000000000;
    double simulation_time1, simulation_time2;
    clock_t Start, End;

    /* addition */
    Start = clock();
    do
    {
         total1 += i + i;
         i++;
    } while (i < j);
    End = clock();
    simulation_time1 = (double)(End - Start) / CLOCKS_PER_SEC;

    /* multiplication */
    Start = clock();
    do
    {
         total2 += i * i * i * i;
         i++;
    } while (i < j);
    End = clock();
    simulation_time2 = (double)(End - Start) / CLOCKS_PER_SEC;

    printf("Total 1 = %u \n", total1);
    printf("Total 2 = %u \n", total2);
    printf("Runtime of Whole Simulation: %f\n"
        "Runtime of Addition:         %f\n"
        "Runtime of Multiplication:   %f\n",
        simulation_time1 + simulation_time2,
        simulation_time1, simulation_time2);

    return 0;
}

这篇关于在C语言循环中获取特定代码部分的时序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 06:16
查看更多