6.1.3 : Le main.cpp

Comme toujours, on commence pas les includes :
1
2
3
4
5
6
7
8
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
#include <random>

//Some doc at : https://en.cppreference.com/w/cpp/header/execution
#include <execution>


Ensuite, la fonction main :
1
int main(int argc, char** argv){


On définit le nombre d'éléments que l'on veut dans nos tableaux :
1
	size_t nbElement(100000000);


On initialise les générateurs de nombre aléatoire, ainsi que le générateur de distribution normale
1
2
3
	std::random_device rd{};
	std::mt19937 generator{rd()};
	std::normal_distribution distribNormal{0.0f, 1.0f};	//Mean = 0, Std = 1


On déclare nos tableaux et on les initialise :
1
	std::vector<float> tabX(nbElement), tabY(nbElement);


On initialise tabX avec notre std::normal_distribution (Il n'est pas possible d'avoir une exécution std::execution::par_unseq à cause de la dépendence arrière due au génrateur de nombre aléatoire, et aussi au fait que les long double de Mersene Twister (std::mt19937 ) ne sont pas supporté). Donc on est obligé de tout appeler sur CPU :
1
2
3
4
5
	std::for_each(tabX.begin(), tabX.end(),
		[&](float & val){
			val = distribNormal(generator);
		}
	);


On initialise tabY :
1
2
3
4
5
	std::for_each(tabY.begin(), tabY.end(), 
		[&](float & val){
			val = distribNormal(generator);
		}
	);


On déclare notre produit scalaire (la somme initiale est 0) :
1
2
3
	float res = std::transform_reduce(std::execution::par_unseq, std::begin(tabX), std::end(tabX), std::begin(tabY),
			0.0f, std::plus{},
			[](float xi, float yi){ return xi * yi; });


On affiche la moyenne :
1
	std::cout << "res = " << res/((float)nbElement) << std::endl;


Puis on termine la fonction main :
1
2
	return 0;
}


Le main.cpp complet :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/***************************************
	Auteur : Pierre Aubert
	Mail : pierre.aubert@lapp.in2p3.fr
	Licence : CeCILL-C
****************************************/
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
#include <random>

//Some doc at : https://en.cppreference.com/w/cpp/header/execution
#include <execution>
int main(int argc, char** argv){
	size_t nbElement(100000000);
	std::random_device rd{};
	std::mt19937 generator{rd()};
	std::normal_distribution distribNormal{0.0f, 1.0f};	//Mean = 0, Std = 1
	std::vector<float> tabX(nbElement), tabY(nbElement);
	std::for_each(tabX.begin(), tabX.end(),
		[&](float & val){
			val = distribNormal(generator);
		}
	);
	std::for_each(tabY.begin(), tabY.end(), 
		[&](float & val){
			val = distribNormal(generator);
		}
	);
	float res = std::transform_reduce(std::execution::par_unseq, std::begin(tabX), std::end(tabX), std::begin(tabY),
			0.0f, std::plus{},
			[](float xi, float yi){ return xi * yi; });
	std::cout << "res = " << res/((float)nbElement) << std::endl;
	return 0;
}


Le fichier main.cpp est disponible ici.