Thread: How to add times elapsed from function inside a loop?

  1. #1
    Registered User
    Join Date
    Apr 2010
    Location
    Vancouver
    Posts
    131

    How to add times elapsed from function inside a loop?

    I have implemented two ways of doing something inside a loop. I'd like to time them to find out which to keep.

    Code:
    for(int i = 0; i < 1000; i++)
    {
        int x = whatever(i);
        foo1(x);
        foo2(x)
    }
    How can I find out the total time of foo1 and foo2? I tried declaring an std::chrono variable outside the for loop and measuring foo1 and food2 with now() but times elapsed can't be added.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,490
    You would need to do
    Code:
    t1 = std::chrono::high_resolution_clock::now();
    for(int i = 0; i < 1000; i++)
    {
        int x = whatever(i);
        foo1(x);
    }
    t2 = std::chrono::high_resolution_clock::now();
    for(int i = 0; i < 1000; i++)
    {
        int x = whatever(i);
        foo2(x);
    }
    t3 = std::chrono::high_resolution_clock::now();
    Then foo1 takes t2-t1 and foo2 takes t3-t2.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 04-12-2017, 03:44 PM
  2. Replies: 1
    Last Post: 02-27-2016, 07:30 PM
  3. Replies: 4
    Last Post: 10-09-2011, 02:11 AM
  4. Replies: 5
    Last Post: 06-23-2009, 03:51 AM
  5. Why does it only loop three times??
    By iguana999 in forum C++ Programming
    Replies: 13
    Last Post: 04-24-2002, 11:03 PM

Tags for this Thread