0

I want to measure the time it takes to call a function.

Here is the code:

for (int i = 0; i < 5; ++i) {
        std::cout << "Pass : " << i << "\n";
        
        const auto t0 = std::chrono::high_resolution_clock::now();
        system1.euler_intregration(0.0166667);
        const auto t1 = std::chrono::high_resolution_clock::now();

        std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count() << "\n";

but the compiler keeps optimising the loop so time is not measured and returns zero.

I have tried using asm("") and __asm__("") as advised here but nothing works for me. I must admit that I don't really know how these asm() functions works so I might be using them in the wrong way.

Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79
t9dupuy
  • 330
  • 1
  • 2
  • 9
  • Side note: [Avoid `high_resolution_clock`](https://stackoverflow.com/a/37440647/4581301). You don't get good guarantees on what type of clock you'll get. – user4581301 Dec 18 '21 at 21:59
  • 4
    add an unavoidable side-effect to the computation. Store the the results of `euler_intregration` somewhere and print them after you've stopped timing. – user4581301 Dec 18 '21 at 22:00
  • What type does `system1` have? If it is self-implemented - include code of your class in the question. Compiler at own discretion can optimize your function depending on it's behavior and literally do nothing when you calling `euler_intregration()` method – Learpcs Dec 18 '21 at 22:05
  • `euler_integration()` was declared `void` but I changed it to `int` and just return 0 and it works (even if I discard to return value) – t9dupuy Dec 18 '21 at 22:11
  • 2
    Following up the other comment, switch the clock to `steady_clock`. You don't want a system time change to affect your timing results. – chris Dec 18 '21 at 22:15
  • I wouldn't trust discarding the return value in all cases, but if it's working for your case, good enough. – user4581301 Dec 18 '21 at 22:29
  • Side note, you don't need `duration_cast` when casting to a more/same precision duration type. – Ranoiaetep Dec 18 '21 at 23:04
  • Why not just run your `euler_integration` 1000 times, and then divide by 1000? – Mike Dunlavey Dec 19 '21 at 17:09

0 Answers0