Skip to content

Instantly share code, notes, and snippets.

@N-Dekker
Last active December 11, 2023 21:35
Show Gist options
  • Save N-Dekker/e43033e03c86373864ed9992d9a3675c to your computer and use it in GitHub Desktop.
Save N-Dekker/e43033e03c86373864ed9992d9a3675c to your computer and use it in GitHub Desktop.
std::function versus template argument
// Related to https://github.com/InsightSoftwareConsortium/ITK/pull/4347
// PERF: Replace `std::function` with template argument MultiThreaderBase ParallelizeImageRegion, ParallelizeImageRegionRestrictDirection
// Niels Dekker, LKEB, Leiden University Medical Center, 2023
#include <itkImageRegion.h>
#include <algorithm>
#include <chrono>
#include <numeric>
#include <vector>
using FunctorType = std::function<void(const itk::ImageRegion<2>&)>;
namespace
{
volatile itk::ImageRegion<2> imageRegion;
void CallStdFunction(FunctorType funcP, const itk::ImageRegion<2>& region)
{
funcP(region);
}
template <typename TFunction>
void CallFunctionTemplate(TFunction funcP, const itk::ImageRegion<2>& region)
{
funcP(region);
}
}
int main()
{
constexpr int n{ 10'000'000 };
volatile int result{};
for (const bool bTemplate : {false, true})
{
using namespace std::chrono;
const auto timePoint = high_resolution_clock::now();
if (bTemplate)
{
for (int i{}; i < n; ++i)
{
CallFunctionTemplate([&result](const itk::ImageRegion<2>& region) {result += region.GetSize()[1]; }, itk::ImageRegion<2>{});
}
}
else
{
for (int i{}; i < n; ++i)
{
CallStdFunction([&result](const itk::ImageRegion<2>& region) {result += region.GetSize()[1]; }, itk::ImageRegion<2>{});
}
}
std::cout << " Duration: "
<< duration_cast<duration<double>>(high_resolution_clock::now() - timePoint).count() << " seconds" << std::endl;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment