Skip to content

Instantly share code, notes, and snippets.

@bwedding
Created June 3, 2019 22:35
Show Gist options
  • Save bwedding/985ecb765453beab3f41996bda52098b to your computer and use it in GitHub Desktop.
Save bwedding/985ecb765453beab3f41996bda52098b to your computer and use it in GitHub Desktop.
#include<stdio.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include <chrono>
using namespace std::chrono;
class ExecutionTimer
{
public:
// Use the best steady clock available
using Clock = std::conditional_t<high_resolution_clock::is_steady,
high_resolution_clock,
steady_clock>;
ExecutionTimer() = default;
inline ~ExecutionTimer()
{
std::string units = " microSeconds";
// Determine whether to print uSecs or mSecs or Secs
double count = duration_cast<microseconds>(Clock::now() - mStart).count();
if (count > 1000)
{
// Convert to milliseconds
units = " milliSeconds";
count /= 1000.0f;
if (count > 1000)
{
// Convert to seconds
units = " Seconds";
count /= 1000.0f;
}
}
std::cout
<< "Elapsed: " << count << units.data() << std::endl;
}
private:
Clock::time_point mStart = Clock::now();
};
int main()
{
int a[] = { 1, 2, 3, 8, 3, 5, 9, 0, 12, 56 }; // 10 elements
int i, *p;
{
ExecutionTimer tm;
for (int x = 0; x < 100000; x++)
for (i = 0; i< sizeof(a[0]) / sizeof(int); i++)
volatile int tmp = a[i];
}
printf("\n\n");
{
ExecutionTimer tm;
for (int x = 0; x < 100000; x++)
for (i = 0; i < (&a)[1] - a; i++)
volatile int tmp = a[i];
}
printf("\n\n");
{
ExecutionTimer tm;
for (int x = 0; x < 100000; x++)
for (p = a; p < (&a)[1]; p++) // even more efficient
volatile int tmp = a[i];
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment