Counting time in C++/CLI

I have app, where i must count time of executing part of C++ function and ASM function. Actually i have problem, times which i get are weird - 0 or about 15600. O ocurs more often. And sometimes, after executing, times looks good, and values are different than 0 and ~15600. Anybody knows why it occurs ? And how to fix it ? Fragment of counting time for executing my app for C++:

auto start = chrono::system_clock::now();
for (int i = 0; i < nThreads; i++)
    xThread[i]->Start(i);
for (int i = 0; i < nThreads; i++)
    xThread[i]->Join();
auto elapsed = chrono::system_clock::now() - start;
long long milliseconds = chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
cppTimer = milliseconds;

Upvotes: 2

Views: 2097

Answers (2)

David Yaw
David Yaw

Reputation: 27864

What you're seeing there is the resolution of your timer. Apparently, chrono::system_clock ticks every 1/64th of a second, or 15,625 microseconds, on your system.

Since you're in C++/CLI and have the .Net library available, I'd switch to using the Stopwatch class. It will generally have a much higher resolution than 1/64th of a second.

Upvotes: 2

tofi9
tofi9

Reputation: 5853

Looks good to me. Except for cast to std::chrono::microseconds and naming it milliseconds.

The snippet I have used for many months now is:

class benchmark {

private:
    typedef std::chrono::high_resolution_clock clock;
    typedef std::chrono::milliseconds milliseconds;

    clock::time_point start;

public:
    benchmark(bool startCounting = true) {
        if(startCounting)
            start = clock::now();
    }

    void reset() {
        start = clock::now();
    }

    // in milliseconds
    double elapsed() {
        milliseconds ms = std::chrono::duration_cast<milliseconds>(clock::now() - start);
        double elapsed_secs = ms.count() / 1000.0;
        return elapsed_secs;
    }
};



// usage
benchmark b;
...
cout << "took " << b.elapsed() << " ms" << endl;

Upvotes: 0

Related Questions