Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <chrono>
- #define EIGEN_NO_DEBUG
- #include <Eigen/Dense>
- void meanStd(const double data[],
- const std::size_t dataSize, const std::size_t dataElementSize,
- double mean[])
- {
- for (std::size_t idxElement = 0; idxElement < dataElementSize; ++idxElement)
- mean[idxElement] = 0;
- for (std::size_t idxData = 0, offset = 0; idxData < dataSize;
- ++idxData, offset += dataElementSize) {
- const double* const dataElm = data + offset;
- for (std::size_t idxElement = 0; idxElement < dataElementSize; ++idxElement)
- mean[idxElement] += dataElm[idxElement];
- }
- for (std::size_t idxElement = 0; idxElement < dataElementSize; ++idxElement)
- mean[idxElement] /= dataSize;
- }
- void meanStdEigen(const double data[], const std::size_t dataSize,
- const std::size_t dataElementSize,
- double mean[/* dataElementSize */])
- {
- Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>>
- dataMat(data, dataElementSize, dataSize);
- Eigen::Map<Eigen::Vector<double, Eigen::Dynamic>>
- meanMat(mean, dataElementSize);
- meanMat = dataMat.rowwise().mean();
- }
- int main()
- {
- const std::size_t dataElementSize = 1000,
- dataSize = 30000,
- a_size = dataSize * dataElementSize,
- N_TIMES = 100;
- // Generate random data
- double* data = new double[a_size];
- for (std::size_t i = 0; i < a_size; ++i)
- data[i] = i + 1;
- double mean[dataElementSize];
- // measure execution time of the raw implementation
- auto startOriginal = std::chrono::high_resolution_clock::now();
- for (std::size_t i = 0; i < N_TIMES; ++i)
- meanStd(data, dataSize, dataElementSize, mean);
- auto endOriginal = std::chrono::high_resolution_clock::now();
- std::chrono::duration<double> elapsedOriginal = endOriginal - startOriginal;
- float elapsed = elapsedOriginal.count() / N_TIMES;
- printf("Low-level) elapsed = %0.3e s\n", elapsed);
- // measure execution time of the Eigen-based implementation
- startOriginal = std::chrono::high_resolution_clock::now();
- for (std::size_t i = 0; i < N_TIMES; ++i)
- meanStdEigen(data, dataSize, dataElementSize, mean);
- endOriginal = std::chrono::high_resolution_clock::now();
- std::chrono::duration<double> elapsedOriginal_Eigen = endOriginal - startOriginal;
- float elapsed_Eigen = elapsedOriginal_Eigen.count() / N_TIMES;
- printf("Eigen) elapsed = %0.3e s\n", elapsed_Eigen);
- printf("> comparison of elapsed times: t_Eigen/t_raw = %0.1f s\n", elapsed_Eigen / elapsed);
- delete[] data;
- return 0;
- }
- // g++ -Wall -Wpedantic -O3 -DNDEBUG -std=c++17 -I"/usr/include/eigen3" test_meanstd.cpp -o test_meanstd.out
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement