为什么我看不到运行时间(纳秒)? [英] Why can I not view the run time (nanoseconds)?

查看:47
本文介绍了为什么我看不到运行时间(纳秒)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查看我的代码的运行时是什么.该代码是我在 Project Euler 问题 5 中的尝试.当我尝试输出运行时间时,它给出了 0ns.

I am trying to view what the run-time on my code is. The code is my attempt at Project Euler Problem 5. When I try to output the run time it gives 0ns.

#define MAX_DIVISOR 20

bool isDivisible(long, int);

int main() {

auto begin = std::chrono::high_resolution_clock::now();

int d = 2;
long inc = 1;
long i = 1;
while (d < (MAX_DIVISOR + 1)) {
    if ((i % d) == 0) {
        inc = i;
        i = inc;
        d++;
    }
    else {
        i += inc;
    }
}
auto end = std::chrono::high_resolution_clock::now();

printf("Run time: %llu ns\n", (std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count())); // Gives 0 here.
std::cout << "ANS: " << i << std::endl;

system("pause");
return 0;

}

推荐答案

你要做的估计并不精确,更好的方法是测量你程序的 CPU 时间消耗(因为其他进程还与您的进程同时运行,因此如果 CPU 密集型任务与您的进程并行运行,则您尝试测量的时间可能会受到很大影响).
因此,如果您想估计代码性能,我的建议是使用已经实现的分析器.

Estimation you are going to do is not precise, better approach is to measure CPU time consumption of you program (because other processes are also running concurrently with you process, so time that you are trying to measure can be greatly affected if CPU intensitive tasks are running in parallel with you process).
So my advise use already implemented profilers if you want to estimate your code performance.

考虑到您的任务,操作系统如果没有提供所需的时间精度,您需要增加您尝试估计的总时间,最简单的方法 - 运行程序 n 次 &计算平均值,此方法提供了这样的优势,即通过平均值 - 您可以消除因与您的进程同时运行的 CPU 密集型任务而产生的错误.

Considering your task, OS if doesn`t provide needed precision for time, you need to increase total time your are trying to estimate, the esiest way - run program n times & calculate the avarage, this method provides such advantage that by avareging - you can eleminate errors that arose from CPU intensitive tasks running concurrently with you process.

这是我如何看待可能实现的代码片段:

Here is code snippet of how I see the possible implementation:

#include <iostream>
using namespace std;

#define MAX_DIVISOR 20

bool isDivisible(long, int);

void doRoutine()
{
  int d = 2;
  long inc = 1;
  long i = 1;
  while (d < (MAX_DIVISOR + 1)) 
  {
        if (isDivisible(i, d)) 
        {
            inc = i;
            i = inc;
            d++;
        }
        else 
        {
            i += inc;
        }
   }
}

int main() {

auto begin = std::chrono::high_resolution_clock::now();
const int nOfTrials = 1000000;

for (int i = 0; i < nOfTrials; ++i)
    doRoutine();

auto end = std::chrono::high_resolution_clock::now();

printf("Run time: %llu ns\n", (std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count()/ nOfTrials)); // Gives 0 here.
std::cout << "ANS: " << i << std::endl;

system("pause");
return 0;

这篇关于为什么我看不到运行时间(纳秒)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆