C++ 轻松测量经过的时间

C++ 轻松测量经过的时间,c++,c,linux,time,measurement,C++,C,Linux,Time,Measurement,我试图用它来测量程序的各个点 我不明白的是为什么前后的值是一样的?我明白这不是最好的方式来分析我的程序,我只是想看看需要多长时间 printf("**MyProgram::before time= %ld\n", time(NULL)); doSomthing(); doSomthingLong(); printf("**MyProgram::after time= %ld\n", time(NULL)); 我试过: struct timeval diff, startTV, endTV;

我试图用它来测量程序的各个点

我不明白的是为什么前后的值是一样的?我明白这不是最好的方式来分析我的程序,我只是想看看需要多长时间

printf("**MyProgram::before time= %ld\n", time(NULL));

doSomthing();
doSomthingLong();

printf("**MyProgram::after time= %ld\n", time(NULL));
我试过:

struct timeval diff, startTV, endTV;

gettimeofday(&startTV, NULL); 

doSomething();
doSomethingLong();

gettimeofday(&endTV, NULL); 

timersub(&endTV, &startTV, &diff);

printf("**time taken = %ld %ld\n", diff.tv_sec, diff.tv_usec);
如何读取
**耗时=0 26339
的结果?这是否意味着26339纳秒=26.3毫秒

时间(NULL)函数将返回自1970年1月1日00:00起经过的秒数。因为,这个函数在程序中的不同时间被调用,所以它总是不同的

在内部,该函数将访问系统的时钟,这就是为什么每次调用时它都返回不同的值。一般来说,对于非函数式语言,函数中可能会有许多副作用和隐藏状态,而仅仅通过查看函数的名称和参数是看不到的。

time(NULL)
返回自1970年1月1日00:00以来经过的秒数()。因此,这两个值之间的差异是处理所用的秒数

int t0 = time(NULL);
doSomthing();
doSomthingLong();
int t1 = time(NULL);

printf ("time = %d secs\n", t1 - t0);

使用
getTimeOfDay()
,可以获得更精细的结果,它以秒为单位返回当前时间,与
time()
一样,也以微秒为单位返回当前时间。

仅限Windows:(Linux标记是在我发布此答案后添加的)

0 26339 = 0.026'339 s =   26339 µs
4 45025 = 4.045'025 s = 4045025 µs
您可以使用获取自系统启动以来经过的毫秒数

long int before = GetTickCount();

// Perform time-consuming operation

long int after = GetTickCount();

它们是相同的,因为doSomething函数的执行速度比计时器的粒度快。尝试:

printf ("**MyProgram::before time= %ld\n", time(NULL));

for(i = 0; i < 1000; ++i) {
    doSomthing();
    doSomthingLong();
}

printf ("**MyProgram::after time= %ld\n", time(NULL));
printf(“**MyProgram::before time=%ld\n”,time(NULL));
对于(i=0;i<1000;++i){
dosomshing();
doSomthingLong();
}
printf(“**MyProgram::after time=%ld\n”,time(NULL));
函数调用
时间(NULL)
将返回自1970年1月1日epoc以来经过的秒数。也许您的意思是计算两个时间戳之间的差异:

size_t start = time(NULL);
doSomthing();
doSomthingLong();

printf ("**MyProgram::time elapsed= %lds\n", time(NULL) - start);
#包括
void f(){
使用名称空间std;
时钟开始=时钟();
编码到时间();
clock_t end=clock();
双倍运行秒=双倍(结束-开始)/时钟秒;
}

time()。这是一个简单的便携式测量,尽管它过于简化。

两个值相同的原因是因为您的长过程不会花费那么长的时间-不到一秒钟。您可以尝试在函数末尾添加一个长循环(for(int i=0;i<100000000;i++)),以确保这是问题所在,然后我们可以从那里开始


如果上述情况属实,您将需要找到不同的系统函数(我知道您在linux上工作,因此我无法帮助您使用函数名)来更准确地测量时间。我确信linux中有一个函数类似于GetTickCount(),您只需要找到它。

第二个程序打印的值是秒和微秒

0 26339 = 0.026'339 s =   26339 µs
4 45025 = 4.045'025 s = 4045025 µs

正如我从你的问题中看到的,看起来你想知道执行某段代码后经过的时间。我想你会很乐意在第二秒看到结果。如果是,请尝试使用
difftime()
函数,如下所示。希望这能解决你的问题

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

time_t start,end;
time (&start);
.
.
.
<your code>
.
.
.
time (&end);
double dif = difftime (end,start);
printf ("Elasped time is %.2lf seconds.", dif );
#包括
#包括
开始、结束的时间;
时间(&开始);
.
.
.
.
.
.
时间(&结束);
双dif=difftime(结束,开始);
printf(“弹性时间为%.2lf秒”,dif);
#包括//时钟
#包括//用于fmod
#包括//用于系统
#包括//延期
使用名称空间std;
int main()
{
时钟t1,t2;
t1=时钟();//第一次捕获
//现在,您的时间跨度循环或代码在这里
//我首先尝试在每次循环运行时显示经过的时间
int ddays=0;//d前缀只是表示此变量将用于显示
int-dhh=0;
int-dmm=0;
int-dss=0;
int loopcount=1000;//只是为了演示,您的循环当然会有所不同
对于(浮点计数=1;计数1-计时器
使用基于
std::chrono
的计时器:

Timer clock; // Timer<milliseconds, steady_clock>

clock.tick();
/* code you want to measure */
clock.tock();

cout << "Run time = " << clock.duration().count() << " ms\n";
如前所述,我们使用一个持续时间保持在
chrono
类型系统中,并执行诸如平均或比较之类的操作(例如,这里这意味着使用
std::chrono::millizes
)。当我们只执行IO时,我们使用
count()
或持续时间的刻度(例如,这里的毫秒数)

2-仪器仪表 任何可调用的函数(函数、函数对象、lambda等)都可以用于基准测试。假设您有一个函数
F
可以通过参数
arg1、arg2
调用,此技术会导致:

cout
/***C++11样式:***
#包括
std::chrono::staddy_clock::time_point begin=std::chrono::staddy_clock::now();
std::chrono::staddy_clock::time_point end=std::chrono::staddy_clock::now();

std::cout从我们看到的情况来看,tv_sec存储经过的秒数,而tv_usec单独存储经过的微秒数。它们不是彼此的转换。因此,必须将它们更改为适当的单位并添加以获得经过的总时间

struct timeval startTV, endTV;

gettimeofday(&startTV, NULL); 

doSomething();
doSomethingLong();

gettimeofday(&endTV, NULL); 

printf("**time taken in microseconds = %ld\n",
    (endTV.tv_sec * 1e6 + endTV.tv_usec - (startTV.tv_sec * 1e6 + startTV.tv_usec))
    );

回答OP的三个具体问题。

“我不明白的是,为什么“之前”和“之后”中的值是相同的?”

第一个问题和示例代码显示
time()
的分辨率为1秒,因此答案必须是这两个函数在不到1秒的时间内执行。但偶尔会执行(显然不合逻辑)如果两个计时器标记跨越1秒边界,则通知1秒

下一个示例使用填充此结构的
gettimeofday()

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};
第二个问题问:“我如何读取
**耗时=0 26339
的结果?这是否意味着26339纳秒=26.3毫秒?”

我的第二个答案是时间
struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

#define BILLION  1000000000L;

int main( int argc, char **argv )
  {
    struct timespec start, stop;
    double accum;

    if( clock_gettime( CLOCK_REALTIME, &start) == -1 ) {
      perror( "clock gettime" );
      exit( EXIT_FAILURE );
    }

    system( argv[1] );

    if( clock_gettime( CLOCK_REALTIME, &stop) == -1 ) {
      perror( "clock gettime" );
      exit( EXIT_FAILURE );
    }

    accum = ( stop.tv_sec - start.tv_sec )
          + ( stop.tv_nsec - start.tv_nsec )
            / BILLION;
    printf( "%lf\n", accum );
    return( EXIT_SUCCESS );
  }
sf::Clock clock;
...
Time time1 = clock.getElapsedTime();
...
Time time2 = clock.restart();
#include <chrono>
#include <type_traits>

using perf_clock = std::conditional<
    std::chrono::high_resolution_clock::is_steady,
    std::chrono::high_resolution_clock,
    std::chrono::steady_clock
>::type;

using floating_seconds = std::chrono::duration<double>;

template<class F, class... Args>
floating_seconds run_test(Func&& func, Args&&... args)
{
   const auto t0 = perf_clock::now();
   std::forward<Func>(func)(std::forward<Args>(args)...);
   return floating_seconds(perf_clock::now() - t0);
} 
struct profiler
{
    std::string name;
    std::chrono::high_resolution_clock::time_point p;
    profiler(std::string const &n) :
        name(n), p(std::chrono::high_resolution_clock::now()) { }
    ~profiler()
    {
        using dura = std::chrono::duration<double>;
        auto d = std::chrono::high_resolution_clock::now() - p;
        std::cout << name << ": "
            << std::chrono::duration_cast<dura>(d).count()
            << std::endl;
    }
};

#define PROFILE_BLOCK(pbn) profiler _pfinstance(pbn)
{
    PROFILE_BLOCK("Some time");
    // your code or function
}
#include <ctime>
#include <cstdio>
#include <iostream>
#include <chrono>
#include <sys/time.h>
using namespace std;
using namespace std::chrono;

void f1()
{
  high_resolution_clock::time_point t1 = high_resolution_clock::now();
  high_resolution_clock::time_point t2 = high_resolution_clock::now();
  double dif = duration_cast<nanoseconds>( t2 - t1 ).count();
  printf ("Elasped time is %lf nanoseconds.\n", dif );
}

void f2()
{
  timespec ts1,ts2;
  clock_gettime(CLOCK_REALTIME, &ts1);
  clock_gettime(CLOCK_REALTIME, &ts2);
  double dif = double( ts2.tv_nsec - ts1.tv_nsec );
  printf ("Elasped time is %lf nanoseconds.\n", dif );
}

void f3()
{
  struct timeval t1,t0;
  gettimeofday(&t0, 0);
  gettimeofday(&t1, 0);
  double dif = double( (t1.tv_usec-t0.tv_usec)*1000);
  printf ("Elasped time is %lf nanoseconds.\n", dif );
}
void f4()
{
  high_resolution_clock::time_point t1 , t2;
  double diff = 0;
  t1 = high_resolution_clock::now() ;
  for(int i = 1; i <= 10 ; i++)
  {
    t2 = high_resolution_clock::now() ;
    diff+= duration_cast<nanoseconds>( t2 - t1 ).count();
    t1 = t2;
  }
  printf ("high_resolution_clock:: Elasped time is %lf nanoseconds.\n", diff/10 );
}

void f5()
{
  timespec ts1,ts2;
  double diff = 0;
  clock_gettime(CLOCK_REALTIME, &ts1);
  for(int i = 1; i <= 10 ; i++)
  {
    clock_gettime(CLOCK_REALTIME, &ts2);
    diff+= double( ts2.tv_nsec - ts1.tv_nsec );
    ts1 = ts2;
  }
  printf ("clock_gettime:: Elasped time is %lf nanoseconds.\n", diff/10 );
}

void f6()
{
  struct timeval t1,t2;
  double diff = 0;
  gettimeofday(&t1, 0);
  for(int i = 1; i <= 10 ; i++)
  {
    gettimeofday(&t2, 0);
    diff+= double( (t2.tv_usec-t1.tv_usec)*1000);
    t1 = t2;
  }
  printf ("gettimeofday:: Elasped time is %lf nanoseconds.\n", diff/10 );
}

int main()
{
  //  f1();
  //  f2();
  //  f3();
  f6();
  f4();
  f5();
  return 0;
}
void expensiveFunction() {
    static rtimers::cxx11::DefaultTimer timer("expensiveFunc");
    auto scopedStartStop = timer.scopedStart();
    // Do something costly...
}
Timer(expensiveFunc): <t> = 6.65289us, std = 3.91685us, 3.842us <= t <= 63.257us (n=731)
std::chrono::system_clock::now()
std::chrono::steady_clock::now()
std::chrono::high_resolution_clock::now()
#include <stdio.h>
#include <chrono>
#include <ctime>

void print_timediff(const char* prefix, const struct timespec& start, const 
struct timespec& end)
{
    double milliseconds = end.tv_nsec >= start.tv_nsec
                        ? (end.tv_nsec - start.tv_nsec) / 1e6 + (end.tv_sec - start.tv_sec) * 1e3
                        : (start.tv_nsec - end.tv_nsec) / 1e6 + (end.tv_sec - start.tv_sec - 1) * 1e3;
    printf("%s: %lf milliseconds\n", prefix, milliseconds);
}

int main()
{
    int i, n = 1000000;
    struct timespec start, end;

    // Test stopwatch
    clock_gettime(CLOCK_MONOTONIC, &start);
    for (i = 0; i < n; ++i) {
        struct timespec dummy;
        clock_gettime(CLOCK_MONOTONIC, &dummy);
    }
    clock_gettime(CLOCK_MONOTONIC, &end);
    print_timediff("clock_gettime", start, end);

    // Test chrono system_clock
    clock_gettime(CLOCK_MONOTONIC, &start);
    for (i = 0; i < n; ++i)
        auto dummy = std::chrono::system_clock::now();
    clock_gettime(CLOCK_MONOTONIC, &end);
    print_timediff("chrono::system_clock::now", start, end);

    // Test chrono steady_clock
    clock_gettime(CLOCK_MONOTONIC, &start);
    for (i = 0; i < n; ++i)
        auto dummy = std::chrono::steady_clock::now();
    clock_gettime(CLOCK_MONOTONIC, &end);
    print_timediff("chrono::steady_clock::now", start, end);

    // Test chrono high_resolution_clock
    clock_gettime(CLOCK_MONOTONIC, &start);
    for (i = 0; i < n; ++i)
        auto dummy = std::chrono::high_resolution_clock::now();
    clock_gettime(CLOCK_MONOTONIC, &end);
    print_timediff("chrono::high_resolution_clock::now", start, end);

    return 0;
}
clock_gettime: 24.484926 milliseconds
chrono::system_clock::now: 85.142108 milliseconds
chrono::steady_clock::now: 87.295347 milliseconds
chrono::high_resolution_clock::now: 84.437838 milliseconds
template <typename clock_t = std::chrono::steady_clock>
struct scoped_timer {
  using duration_t = typename clock_t::duration;
  const std::function<void(const duration_t&)> callback;
  const std::chrono::time_point<clock_t> start;

  scoped_timer(const std::function<void(const duration_t&)>& finished_callback) :
      callback(finished_callback), start(clock_t::now()) { }
  scoped_timer(std::function<void(const duration_t&)>&& finished_callback) :
      callback(finished_callback), start(clock_t::now()) { }
  ~scoped_timer() { callback(clock_t::now() - start); }
};
void test(bool should_throw) {
  scoped_timer<> t([](const scoped_timer<>::duration_t& elapsed) {
    auto e = std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(elapsed).count();
    std::cout << "took " << e << "ms" << std::endl;
  });

  std::this_thread::sleep_for(std::chrono::seconds(1));

  if (should_throw)
    throw nullptr;

  std::this_thread::sleep_for(std::chrono::seconds(1));
}
#include <ctime>
#include <functional>

using namespace std;

void f() {
  clock_t begin = clock();

  // ...code to measure time...

  clock_t end = clock();

  function<double(double, double)> convtime = [](clock_t begin, clock_t end)
  {
     return double(end - begin) / CLOCKS_PER_SEC;
  };

  printf("Elapsed time: %.2g sec\n", convtime(begin, end));

}
void test_time_measure(std::vector<int> arr) {
  TimeMeasure<chrono::microseconds> time_mea;  // create time measure obj
  std::sort(begin(arr), end(arr));
}