#define Iter 10000 #define cell 100 uint8_t potenArr[cell]; // СТОГ uint8_t needle = 0; // Иголка uint32_t startTime = 0; // время начала поиска uint32_t endTime = 0; // время завершения поиска uint32_t calculationStartTime = 0; uint32_t calculationEndTime = 0; uint32_t Time_poslMetod = 0; uint32_t Time_randMetod = 0;
// Проводим испытания Iter раз for(uint32_t j = 0; j <= Iter; j++){ // Очищаем массив с предыдущим значением cleanArr(); // Бросаем иглу в стог needle = random(cell + 1); potenArr[needle] = 1; // Ищем иглу двумя методами и сохраняем время для каждого poslMetod(); randMetod(); }
void poslMetod(){ startTime = millis(); for(uint16_t i = 0; i < cell; i++){ if(potenArr[i] == 1){ endTime = millis() - startTime; break; } } Time_poslMetod += endTime; }
void randMetod(){ startTime = millis(); for(;;){ uint16_t r = random(cell + 1); if(potenArr[r] == 1){ endTime = millis() - startTime; break; } } Time_randMetod += endTime; }
#define Iter 10000 #define cell 100 uint8_t potenArr[cell]; // СТОГ uint8_t needle = 0; // Иголка, будем присваивать ей случайное значение для номера массива uint32_t startTime = 0; // время начала поиска uint32_t endTime = 0; // время завершения поиска uint32_t calculationStartTime = 0; uint32_t calculationEndTime = 0; uint32_t Time_poslMetod = 0; uint32_t Time_randMetod = 0; void poslMetod(); void randMetod(); void cleanArr(); void DataOutPrint(); void setup() { randomSeed(analogRead(A0)); Serial.begin(115200); } void loop() { Time_poslMetod = 0; Time_randMetod = 0; Serial.println(" "); Serial.println("Start"); calculationStartTime = millis(); // Проводим испытания Iter раз for(uint32_t j = 0; j <= Iter; j++){ // Очищаем массив с предыдущим значением cleanArr(); // Рандомим иглу и кидаем ее в стог needle = random(cell + 1); potenArr[needle] = 1; // Ищем эту иглу двумя способами и сохраняем время для каждого poslMetod(); randMetod(); } // Выводим среднее время для каждого метода DataOutPrint(); delay(2000); } void poslMetod(){ startTime = millis(); for(uint16_t i = 0; i < cell; i++){ if(potenArr[i] == 1){ endTime = millis() - startTime; break; } } Time_poslMetod += endTime; } void randMetod(){ startTime = millis(); for(;;){ uint16_t r = random(cell + 1); if(potenArr[r] == 1){ endTime = millis() - startTime; break; } } Time_randMetod += endTime; } void cleanArr(){ for(uint16_t i = 0; i < cell; i++){ potenArr[i] = 0; } } void DataOutPrint(){ calculationEndTime = (millis() - calculationStartTime)/1000; float OUTposl = (float)Time_poslMetod/Iter; float OUTrand = (float)Time_randMetod/Iter; Serial.println(" "); Serial.print("Number of iterations = "); Serial.println(Iter); Serial.print("Time for calculate (sec) = "); Serial.println(calculationEndTime); Serial.print("Posledovatelniy metod - AverageTime (ms) = "); Serial.println(OUTposl,3); Serial.print("Randomniy metod - AverageTime (ms) = "); Serial.println(OUTrand,3); }
Source: https://habr.com/ru/post/439336/