My latest CPP code:
#include <iostream>
#include <Eigen/Dense>
#include <chrono>
using namespace std;
using Eigen::Vector3d;
using namespace std::chrono;
struct KPS {
Vector3d v_wind_tether;
Vector3d v_apparent;
Vector3d last_tether_drag;
} ;
KPS kps;
double calc_drag(KPS& s, Vector3d& v_segment, Vector3d& unit_vector, double rho, Vector3d& v_app_perp, double area)
{
s.v_apparent = s.v_wind_tether - v_segment;
double v_app_norm = s.v_apparent.norm();
v_app_perp = s.v_apparent - s.v_apparent.dot(unit_vector) * unit_vector;
s.last_tether_drag = -0.5 * rho * v_app_perp.norm() * area * v_app_perp;
return v_app_norm;
}
int main()
{
// std::cout << kps.v_wind_tether << std::endl;
Vector3d v_segment(0.1,0.2,0.3); Vector3d unit_vector(0.0,1,0); double rho = 1.0;
Vector3d v_app_perp(10,0,0); double area = 0.3;
double v_app_norm;
auto start = high_resolution_clock::now();
for(int i=0; i < 100000; i++) {
v_app_norm = calc_drag(kps, v_segment, unit_vector, rho, v_app_perp, area);
}
auto stop = high_resolution_clock::now();
cout << "calc_drag needs "
<< ((stop - start).count())/100000
<< " ns." << endl;
}
And my CMakeLists.txt:
cmake_minimum_required(VERSION 3.0)
project(Tutorial)
find_package (Eigen3 3.3 REQUIRED NO_MODULE)
add_executable(${PROJECT_NAME} "main.cpp")
target_link_libraries (${PROJECT_NAME} Eigen3::Eigen)
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif()
set(CMAKE_CXX_FLAGS "-Wall -Wextra")
set(CMAKE_CXX_FLAGS_DEBUG "-g")
set(CMAKE_CXX_FLAGS_RELEASE "-O2")
Which gives an execution time of 5ns with -O2 optimization level, the same level I used for Julia.
But measuring these very short times is tricky on C++.