int main( ) { execute( Seq( If( True( ), Print( String( "hello " ) ), Print( True( ) ) ), If( Or( False( ), Neg( True( ) ) ), Print( Unit( ) ), Print( String( "world!\n" ) ) ) ) ); execute( Seq( When( True( ), Print( String( "hello " ) ) ), Unless( False( ), Print( String( "world!\n" ) ) ) ) ); execute( Print( Print( Seq( Print( True( ) ), Print( False( ) ) ) ) ) ); execute( Print( Concat( String( "4" ), Show( True( ) ) ) ) ); assert( value_to_bool( execute( IsDefined( String( "not defined" ) ) ) ) == false ); execute( Seq( Set( String( "SomeVar" ), String( "12" ) ), Seq( Print( Get( String( "SomeVar" ) ) ), Seq( Set( Concat( String( "S" ), String( "omeVar" ) ), String( "345\n" ) ), Print( Get( Concat( String( "Some" ), String( "Var" ) ) ) ) ) ) ) ); execute( Seq( If( True( ), Set( String( "hello " ), String( "hellos \n" ) ), Print( True( ) ) ), Print( Get( String( "hello " ) ) ) ) ); execute( Seq( Scope( Set( String( "hi" ), True( ) ) ), Print( IsDefined( String( "hi" ) ) ) ) ); assert( value_to_bool( execute( Seq( Seq( Set( String( "var" ), False( ) ), Scope( Set( String( "var" ), True( ) ) ) ), Get( String( "var" ) ) ) ) ) ); execute( Seq( Seq( Set( String( "b1" ), True( ) ), Set( String( "b2" ), True( ) ) ), While( Or( Get( String( "b1" ) ), Get( String( "b2" ) ) ), If( Get( String( "b1" ) ), Seq( Set( String( "b1" ), False( ) ), Print( String( "Hello" ) ) ), Seq( Set( String( "b2" ), False( ) ), Print( String( "World" ) ) ) ) ) ) ); }
bool ut11::detail::TestStageImpl::Run(out::Output& output) { if (!m_once.description.empty()) { output.OnInfo(m_once.description); return true; } auto runInsideTryCatch = [&](std::function<void(void)> func) -> bool { try { func(); } catch (const ut11::detail::TestFailedException& ex) { output.OnError(ex.GetLine(), ex.GetFile(), ex.GetMessage()); return false; } catch(const std::exception& ex) { output.OnError(ex); return false; } catch(...) { output.OnUnknownError(); return false; } return true; }; auto theFinallyFunction = [&]() -> void { output.EndTest(); Finally(output); }; auto theGivenWhenThenFinallyFunctions = [&]() -> void { output.BeginTest(); Given(output); When(output); Then(output); theFinallyFunction(); }; if (!runInsideTryCatch(theGivenWhenThenFinallyFunctions)) { runInsideTryCatch(theFinallyFunction); return false; } return true; }
int main(int argc, char* argv[]) { double starttime, finishtime, runtime; // i know it doesn't scale, but double pointers are ugly long *taskids[32]; pthread_t threads[32]; int rc; long t; float* tempPtr; starttime = When(); numThreads = atoi(argv[1]); if (numThreads > 32) { printf("\nCurrent code won't scale above 32 threads."); } ptrFrom = &arrFrom[0]; ptrTo = &arrTo[0]; initArrays(); steadyState = 0; pthread_mutex_init(&critical_steady, NULL); pthread_barrier_init(&barrier_first,NULL,numThreads+1); pthread_barrier_init(&barrier_second,NULL,numThreads+1); for(t=0; t<numThreads; t++) { taskids[t] = (long *) malloc(sizeof(long)); *taskids[t] = t; //printf("Creating thread %ld\n", t+1); rc = pthread_create(&threads[t], NULL, iterOverMyRows, (void *) taskids[t]); } while (!steadyState) { steadyState = 1; pthread_barrier_wait(&barrier_first); pthread_barrier_wait(&barrier_second); iterCount++; tempPtr = ptrFrom; ptrFrom = ptrTo; ptrTo = tempPtr; } // start global count cells50 = 0; pthread_mutex_init(&critical_count, NULL); for(t=0; t<numThreads; t++) { taskids[t] = (long *) malloc(sizeof(long)); *taskids[t] = t+1; //printf("Creating thread %ld\n", t+1); rc = pthread_create(&threads[t], NULL, countCells50, (void *) taskids[t]); } for(t=0;t<numThreads;t++) { rc = pthread_join(threads[t],NULL); } finishtime = When(); printf("\nNumber of iterations: %d", iterCount); printf("\nNumber of cells w/ temp greater than 50: %d", cells50); runtime = finishtime - starttime; printf("\nTime taken: %f\n", runtime); //pthread_exit(NULL); }
virtual void Run() { Given("an entity component store with added entities and with components", [&]() { m_entityComponentStore = ecs::EntityComponentStore<int>(); m_actualEntities = std::vector<int>(); m_entities = { 1, 2, 3, 4, 5 }; for (auto entity : m_entities) m_entityComponentStore.addEntity(entity); m_entitiesWithStringComponent.push_back(m_entities[2]); m_entitiesWithIntComponent.push_back(m_entities[2]); m_entitiesWithIntComponent.push_back(m_entities[3]); m_expectedStringComponentValue = std::string("test_component1"); m_expectedIntComponentValue = 7; for (auto entity : m_entitiesWithStringComponent) m_entityComponentStore.addComponent(entity, m_expectedStringComponentValue); for (auto entity : m_entitiesWithIntComponent) m_entityComponentStore.addComponent(entity, m_expectedIntComponentValue); }); Then("getting the string component of an entity gives the expected value", [&]() { std::string component = m_entityComponentStore.getComponentOfEntity<std::string>(m_entitiesWithStringComponent[0]); AssertThat(component, ut11::Is::EqualTo(m_expectedStringComponentValue)); }); Then("getting the int component of an entity gives the expected value", [&]() { int component = m_entityComponentStore.getComponentOfEntity<int>(m_entitiesWithIntComponent[0]); AssertThat(component, ut11::Is::EqualTo(m_expectedIntComponentValue)); }); Then("getting a component of an entity that does not exist throws the expected exception", [&]() { AssertThat([&]() { m_entityComponentStore.getComponentOfEntity<std::string>(100); }, ut11::Will::Throw<ecs::EntityNotFoundException>()); }); Then("getting a component of an entity that does not have that component throws the expected exception", [&]() { AssertThat([&]() { m_entityComponentStore.getComponentOfEntity<std::string>(m_entities[4]); }, ut11::Will::Throw<ecs::ComponentNotFoundException>()); }); When("getting all entities", [&]() { m_actualEntities = m_entityComponentStore.getAllEntities(); }); Then("the expected entities are returned", [&]() { AssertThat(m_actualEntities, ut11::Is::Iterable::EquivalentTo(m_entities)); }); When("getting all entities with string components", [&]() { m_actualEntities = m_entityComponentStore.getAllEntitiesFor<std::string>(); }); Then("the expected entities are returned", [&]() { AssertThat(m_actualEntities, ut11::Is::Iterable::EquivalentTo(m_entitiesWithStringComponent)); }); When("getting all entities with int components", [&]() { m_actualEntities = m_entityComponentStore.getAllEntitiesFor<int>(); }); Then("the expected entities are returned", [&]() { AssertThat(m_actualEntities, ut11::Is::Iterable::EquivalentTo(m_entitiesWithIntComponent)); }); }
virtual void Run() { Given("an output stream and output", [&]() { m_actualOutput.str(""); m_output = std::unique_ptr<ut11::out::StdOutput>(new ut11::out::StdOutput(m_actualOutput)); }); When("begin and end without running any tests", [&]() { m_output->Begin(); m_output->Finish(10, 7); }); Then("the output is as expected", [&]() { AssertThat(m_actualOutput.str(), ut11::Is::EqualTo("\nFinished!\nRan: 10\nSucceeded: 7\n")); }); When("running a test fixture with just a Then", [&]() { m_output->Begin(); m_output->BeginFixture("fixture"); m_output->BeginTest(); m_output->BeginThen("then"); m_output->EndThen("then"); m_output->EndTest(); m_output->EndFixture("fixture"); m_output->Finish(1, 1); }); Then("the output is as expected", [&]() { auto stringVal = m_actualOutput.str(); auto startOfTime = stringVal.find('['); auto endOfTime = stringVal.find(']'); stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1); AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\t\t\tThen: then \n\nFinished!\nRan: 1\nSucceeded: 1\n")); }); When("running two test fixtures with just a Then", [&]() { m_output->Begin(); m_output->BeginFixture("fixture"); m_output->BeginTest(); m_output->BeginThen("then"); m_output->EndThen("then"); m_output->EndTest(); m_output->EndFixture("fixture"); m_output->BeginFixture("fixture2"); m_output->BeginTest(); m_output->BeginThen("then2"); m_output->EndThen("then2"); m_output->EndTest(); m_output->EndFixture("fixture2"); m_output->Finish(2, 2); }); Then("the output is as expected", [&]() { auto stringVal = m_actualOutput.str(); auto startOfTime = stringVal.find('['); auto endOfTime = stringVal.find(']'); stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1); startOfTime = stringVal.find('['); endOfTime = stringVal.find(']'); stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1); AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\t\t\tThen: then \nFixture: fixture2\n\t\t\tThen: then2 \n\nFinished!\nRan: 2\nSucceeded: 2\n")); }); When("running a test fixture with just a When and Then", [&]() { m_output->Begin(); m_output->BeginFixture("fixture"); m_output->BeginTest(); m_output->BeginWhen("when"); m_output->EndWhen("then"); m_output->BeginThen("then"); m_output->EndThen("then"); m_output->EndTest(); m_output->EndFixture("fixture"); m_output->Finish(1, 1); }); Then("the output is as expected", [&]() { auto stringVal = m_actualOutput.str(); auto startOfTime = stringVal.find('['); auto endOfTime = stringVal.find(']'); stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1); AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\t\tWhen: when\n\t\t\tThen: then \n\nFinished!\nRan: 1\nSucceeded: 1\n")); }); When("running a test fixture with a Given When and Then", [&]() { m_output->Begin(); m_output->BeginFixture("fixture"); m_output->BeginTest(); m_output->BeginGiven("given"); m_output->EndGiven("given"); m_output->BeginWhen("when"); m_output->EndWhen("then"); m_output->BeginThen("then"); m_output->EndThen("then"); m_output->EndTest(); m_output->EndFixture("fixture"); m_output->Finish(1, 1); }); Then("the output is as expected", [&]() { auto stringVal = m_actualOutput.str(); auto startOfTime = stringVal.find('['); auto endOfTime = stringVal.find(']'); stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1); AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\tGiven: given\n\t\tWhen: when\n\t\t\tThen: then \n\nFinished!\nRan: 1\nSucceeded: 1\n")); }); When("running a test fixture with a Given When Then Finally", [&]() { m_output->Begin(); m_output->BeginFixture("fixture"); m_output->BeginTest(); m_output->BeginGiven("given"); m_output->EndGiven("given"); m_output->BeginWhen("when"); m_output->EndWhen("then"); m_output->BeginThen("then"); m_output->EndThen("then"); m_output->BeginFinally("finally"); m_output->EndFinally("finally"); m_output->EndTest(); m_output->EndFixture("fixture"); m_output->Finish(1, 1); }); Then("the output is as expected", [&]() { auto stringVal = m_actualOutput.str(); auto startOfTime = stringVal.find('['); auto endOfTime = stringVal.find(']'); stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1); AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\tGiven: given\n\t\tWhen: when\n\t\t\tThen: then \n\tFinally: finally\n\nFinished!\nRan: 1\nSucceeded: 1\n")); }); When("running a test fixture with multiple tests with a Given When Then Finally where the Given and Whens repeat", [&]() { m_output->Begin(); m_output->BeginFixture("fixture"); m_output->BeginTest(); m_output->BeginGiven("given"); m_output->EndGiven("given"); m_output->BeginWhen("when"); m_output->EndWhen("then"); m_output->BeginThen("then"); m_output->EndThen("then"); m_output->BeginFinally("finally"); m_output->EndFinally("finally"); m_output->EndTest(); m_output->BeginTest(); m_output->BeginGiven("given"); m_output->EndGiven("given"); m_output->BeginWhen("when"); m_output->EndWhen("then"); m_output->BeginThen("then2"); m_output->EndThen("then2"); m_output->BeginFinally("finally"); m_output->EndFinally("finally"); m_output->EndTest(); m_output->EndFixture("fixture"); m_output->Finish(1, 1); }); Then("the output is as expected", [&]() { auto stringVal = m_actualOutput.str(); auto startOfTime = stringVal.find('['); auto endOfTime = stringVal.find(']'); stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1); startOfTime = stringVal.find('['); endOfTime = stringVal.find(']'); stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1); AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\tGiven: given\n\t\tWhen: when\n\t\t\tThen: then \n\t\t\tThen: then2 \n\tFinally: finally\n\nFinished!\nRan: 1\nSucceeded: 1\n")); }); When("running a test fixture with a When Then Finally", [&]() { m_output->Begin(); m_output->BeginFixture("fixture"); m_output->BeginTest(); m_output->BeginWhen("when"); m_output->EndWhen("then"); m_output->BeginThen("then"); m_output->EndThen("then"); m_output->BeginFinally("finally"); m_output->EndFinally("finally"); m_output->EndTest(); m_output->EndFixture("fixture"); m_output->Finish(1, 1); }); Then("the output is as expected", [&]() { auto stringVal = m_actualOutput.str(); auto startOfTime = stringVal.find('['); auto endOfTime = stringVal.find(']'); stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1); AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\t\tWhen: when\n\t\t\tThen: then \n\tFinally: finally\n\nFinished!\nRan: 1\nSucceeded: 1\n")); }); When("running a test fixture with a Then Finally", [&]() { m_output->Begin(); m_output->BeginFixture("fixture"); m_output->BeginTest(); m_output->BeginThen("then"); m_output->EndThen("then"); m_output->BeginFinally("finally"); m_output->EndFinally("finally"); m_output->EndTest(); m_output->EndFixture("fixture"); m_output->Finish(1, 1); }); Then("the output is as expected", [&]() { auto stringVal = m_actualOutput.str(); auto startOfTime = stringVal.find('['); auto endOfTime = stringVal.find(']'); stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1); AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\t\t\tThen: then \n\tFinally: finally\n\nFinished!\nRan: 1\nSucceeded: 1\n")); }); When("running a test fixture with a Given When Then Finally and the Then fails with an std::exception", [&]() { m_output->Begin(); m_output->BeginFixture("fixture"); m_output->BeginTest(); m_output->BeginGiven("given"); m_output->EndGiven("given"); m_output->BeginWhen("when"); m_output->EndWhen("then"); m_output->BeginThen("then"); m_output->OnError(std::runtime_error("error")); m_output->EndThen("then"); m_output->BeginFinally("finally"); m_output->EndFinally("finally"); m_output->EndTest(); m_output->EndFixture("fixture"); m_output->Finish(1, 0); }); Then("the output is as expected", [&]() { auto stringVal = m_actualOutput.str(); auto startOfTime = stringVal.find('['); startOfTime = stringVal.substr(startOfTime + 1).find('[') + startOfTime; auto endOfTime = stringVal.find(']'); endOfTime = stringVal.substr(endOfTime + 1).find(']') + endOfTime + 1; stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1); AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\tGiven: given\n\t\tWhen: when\n\t\t\tThen: then\n\tFailed: std::exception was thrown [what(): error]\n\tFinally: finally\n\nFinished!\nRan: 1\nSucceeded: 0\n")); }); When("running a test fixture with a Given When Then Finally and the Then fails with an unknown error", [&]() { m_output->Begin(); m_output->BeginFixture("fixture"); m_output->BeginTest(); m_output->BeginGiven("given"); m_output->EndGiven("given"); m_output->BeginWhen("when"); m_output->EndWhen("then"); m_output->BeginThen("then"); m_output->OnUnknownError(); m_output->EndThen("then"); m_output->BeginFinally("finally"); m_output->EndFinally("finally"); m_output->EndTest(); m_output->EndFixture("fixture"); m_output->Finish(1, 0); }); Then("the output is as expected", [&]() { auto stringVal = m_actualOutput.str(); auto startOfTime = stringVal.find('['); startOfTime = stringVal.substr(startOfTime + 1).find('[') + startOfTime; auto endOfTime = stringVal.find(']'); endOfTime = stringVal.substr(endOfTime + 1).find(']') + endOfTime + 1; stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1); AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\tGiven: given\n\t\tWhen: when\n\t\t\tThen: then\n\tFailed: Unknown Error\n\tFinally: finally\n\nFinished!\nRan: 1\nSucceeded: 0\n")); }); When("running a test fixture with a Given When Then Finally and the Then fails", [&]() { m_output->Begin(); m_output->BeginFixture("fixture"); m_output->BeginTest(); m_output->BeginGiven("given"); m_output->EndGiven("given"); m_output->BeginWhen("when"); m_output->EndWhen("then"); m_output->BeginThen("then"); m_output->OnError(10, "file", "error"); m_output->EndThen("then"); m_output->BeginFinally("finally"); m_output->EndFinally("finally"); m_output->EndTest(); m_output->EndFixture("fixture"); m_output->Finish(1, 0); }); Then("the output is as expected", [&]() { auto stringVal = m_actualOutput.str(); auto startOfTime = stringVal.find('['); startOfTime = stringVal.substr(startOfTime + 1).find('[') + startOfTime; auto endOfTime = stringVal.find(']'); endOfTime = stringVal.substr(endOfTime + 1).find(']') + endOfTime + 1; stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1); AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\tGiven: given\n\t\tWhen: when\n\t\t\tThen: then\n\tFailed: [10:file] error\n\tFinally: finally\n\nFinished!\nRan: 1\nSucceeded: 0\n")); }); When("running a test fixture with a Given When Finally and the When fails", [&]() { m_output->Begin(); m_output->BeginFixture("fixture"); m_output->BeginTest(); m_output->BeginGiven("given"); m_output->EndGiven("given"); m_output->BeginWhen("when"); m_output->OnError(10, "file", "error"); m_output->EndWhen("then"); m_output->BeginFinally("finally"); m_output->EndFinally("finally"); m_output->EndTest(); m_output->EndFixture("fixture"); m_output->Finish(1, 0); }); Then("the output is as expected", [&]() { auto stringVal = m_actualOutput.str(); auto startOfTime = stringVal.find('['); startOfTime = stringVal.substr(startOfTime + 1).find('[') + startOfTime; auto endOfTime = stringVal.find(']'); endOfTime = stringVal.substr(endOfTime + 1).find(']') + endOfTime + 1; stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1); AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\tGiven: given\n\t\tWhen: when\n\tFailed: [10:file] error\n\tFinally: finally\n\nFinished!\nRan: 1\nSucceeded: 0\n")); }); When("running a test fixture with a Given Finally and the Given fails", [&]() { m_output->Begin(); m_output->BeginFixture("fixture"); m_output->BeginTest(); m_output->BeginGiven("given"); m_output->OnError(10, "file", "error"); m_output->EndGiven("given"); m_output->BeginFinally("finally"); m_output->EndFinally("finally"); m_output->EndTest(); m_output->EndFixture("fixture"); m_output->Finish(1, 0); }); Then("the output is as expected", [&]() { auto stringVal = m_actualOutput.str(); auto startOfTime = stringVal.find('['); startOfTime = stringVal.substr(startOfTime + 1).find('[') + startOfTime; auto endOfTime = stringVal.find(']'); endOfTime = stringVal.substr(endOfTime + 1).find(']') + endOfTime + 1; stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1); AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\tGiven: given\n\tFailed: [10:file] error\n\tFinally: finally\n\nFinished!\nRan: 1\nSucceeded: 0\n")); }); When("running a test fixture with a Given Finally and the Finally fails", [&]() { m_output->Begin(); m_output->BeginFixture("fixture"); m_output->BeginTest(); m_output->BeginGiven("given"); m_output->EndGiven("given"); m_output->BeginFinally("finally"); m_output->OnError(10, "file", "error"); m_output->EndFinally("finally"); m_output->EndTest(); m_output->EndFixture("fixture"); m_output->Finish(1, 0); }); Then("the output is as expected", [&]() { auto stringVal = m_actualOutput.str(); auto startOfTime = stringVal.find('['); startOfTime = stringVal.substr(startOfTime + 1).find('[') + startOfTime; auto endOfTime = stringVal.find(']'); endOfTime = stringVal.substr(endOfTime + 1).find(']') + endOfTime + 1; stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1); AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\tGiven: given\n\tFinally: finally\n\tFailed: [10:file] error\n\nFinished!\nRan: 1\nSucceeded: 0\n")); }); }
int main(int argc, char **argv) { FILE *out; /* Output data file */ char s[255],s2[255],delim[255],*pstr; /* Generic strings */ int *memcache; /* used to flush cache */ int len_buf_align, /* meaningful when args.cache is 0. buflen */ /* rounded up to be divisible by 8 */ num_buf_align; /* meaningful when args.cache is 0. number */ /* of aligned buffers in memtmp */ int c, /* option index */ i, j, n, nq, /* Loop indices */ asyncReceive=0, /* Pre-post a receive buffer? */ bufalign=16*1024,/* Boundary to align buffer to */ errFlag, /* Error occurred in inner testing loop */ nrepeat, /* Number of time to do the transmission */ nrepeat_const=0,/* Set if we are using a constant nrepeat */ len, /* Number of bytes to be transmitted */ inc=0, /* Increment value */ perturbation=DEFPERT, /* Perturbation value */ pert, start= 1, /* Starting value for signature curve */ end=MAXINT, /* Ending value for signature curve */ streamopt=0, /* Streaming mode flag */ reset_connection;/* Reset the connection between trials */ ArgStruct args; /* Arguments for all the calls */ double t, t0, t1, t2, /* Time variables */ tlast, /* Time for the last transmission */ latency; /* Network message latency */ Data bwdata[NSAMP]; /* Bandwidth curve data */ int integCheck=0; /* Integrity check */ /* Initialize vars that may change from default due to arguments */ strcpy(s, "np.out"); /* Default output file */ /* Let modules initialize related vars, and possibly call a library init function that requires argc and argv */ Init(&args, &argc, &argv); /* This will set args.tr and args.rcv */ args.preburst = 0; /* Default to not bursting preposted receives */ args.bidir = 0; /* Turn bi-directional mode off initially */ args.cache = 1; /* Default to use cache */ args.upper = end; args.host = NULL; args.soffset=0; /* default to no offsets */ args.roffset=0; args.syncflag=0; /* use normal mpi_send */ args.port = DEFPORT; /* just in case the user doesn't set this. */ /* TCGMSG launches NPtcgmsg with a -master master_hostname * argument, so ignore all arguments and set them manually * in netpipe.c instead. */ #if ! defined(TCGMSG) /* Parse the arguments. See Usage for description */ while ((c = getopt(argc, argv, "SO:rIiszgfaB2h:p:o:l:u:b:m:n:t:c:d:D:P:")) != -1) { switch(c) { case 'O': strcpy(s2,optarg); strcpy(delim,","); if((pstr=strtok(s2,delim))!=NULL) { args.soffset=atoi(pstr); if((pstr=strtok((char *)NULL,delim))!=NULL) args.roffset=atoi(pstr); else /* only got one token */ args.roffset=args.soffset; } else { args.soffset=0; args.roffset=0; } printf("Transmit buffer offset: %d\nReceive buffer offset: %d\n",args.soffset,args.roffset); break; case 'p': perturbation = atoi(optarg); if( perturbation > 0 ) { printf("Using a perturbation value of %d\n\n", perturbation); } else { perturbation = 0; printf("Using no perturbations\n\n"); } break; case 'B': if(integCheck == 1) { fprintf(stderr, "Integrity check not supported with prepost burst\n"); exit(-1); } args.preburst = 1; asyncReceive = 1; printf("Preposting all receives before a timed run.\n"); printf("Some would consider this cheating,\n"); printf("but it is needed to match some vendor tests.\n"); fflush(stdout); break; case 'I': args.cache = 0; printf("Performance measured without cache effects\n\n"); fflush(stdout); break; case 'o': strcpy(s,optarg); printf("Sending output to %s\n", s); fflush(stdout); break; case 's': streamopt = 1; printf("Streaming in one direction only.\n\n"); #if defined(TCP) && ! defined(INFINIBAND) printf("Sockets are reset between trials to avoid\n"); printf("degradation from a collapsing window size.\n\n"); #endif args.reset_conn = 1; printf("Streaming does not provide an accurate\n"); printf("measurement of the latency since small\n"); printf("messages may get bundled together.\n\n"); if( args.bidir == 1 ) { printf("You can't use -s and -2 together\n"); exit(0); } fflush(stdout); break; case 'l': start = atoi(optarg); if (start < 1) { fprintf(stderr,"Need a starting value >= 1\n"); exit(0); } break; case 'u': end = atoi(optarg); break; #if defined(TCP) && ! defined(INFINIBAND) case 'b': /* -b # resets the buffer size, -b 0 keeps system defs */ args.prot.sndbufsz = args.prot.rcvbufsz = atoi(optarg); break; #endif case '2': args.bidir = 1; /* Both procs are transmitters */ /* end will be maxed at sndbufsz+rcvbufsz */ printf("Passing data in both directions simultaneously.\n"); printf("Output is for the combined bandwidth.\n"); #if defined(TCP) && ! defined(INFINIBAND) printf("The socket buffer size limits the maximum test size.\n\n"); #endif if( streamopt ) { printf("You can't use -s and -2 together\n"); exit(0); } break; case 'h': args.tr = 1; /* -h implies transmit node */ args.rcv = 0; args.host = (char *)malloc(strlen(optarg)+1); strcpy(args.host, optarg); break; #ifdef DISK case 'd': args.tr = 1; /* -d to specify input/output file */ args.rcv = 0; args.prot.read = 0; args.prot.read_type = 'c'; args.prot.dfile_name = (char *)malloc(strlen(optarg)+1); strcpy(args.prot.dfile_name, optarg); break; case 'D': if( optarg[0] == 'r' ) args.prot.read = 1; else args.prot.read = 0; args.prot.read_type = optarg[1]; break; #endif case 'i': if(args.preburst == 1) { fprintf(stderr, "Integrity check not supported with prepost burst\n"); exit(-1); } integCheck = 1; perturbation = 0; start = sizeof(int)+1; /* Start with integer size */ printf("Doing an integrity check instead of measuring performance\n"); fflush(stdout); break; #if defined(MPI) case 'z': args.source_node = -1; printf("Receive using the ANY_SOURCE flag\n"); fflush(stdout); break; case 'a': asyncReceive = 1; printf("Preposting asynchronous receives\n"); fflush(stdout); break; case 'S': args.syncflag=1; fprintf(stderr,"Using synchronous sends\n"); break; #endif #if defined(MPI2) case 'g': if(args.prot.no_fence == 1) { fprintf(stderr, "-f cannot be used with -g\n"); exit(-1); } args.prot.use_get = 1; printf("Using MPI-2 Get instead of Put\n"); break; case 'f': if(args.prot.use_get == 1) { fprintf(stderr, "-f cannot be used with -g\n"); exit(-1); } args.prot.no_fence = 1; bufalign = 0; printf("Buffer alignment off (Required for no fence)\n"); break; #endif /* MPI2 */ #if defined(INFINIBAND) case 'm': switch(atoi(optarg)) { case 256: args.prot.ib_mtu = MTU256; break; case 512: args.prot.ib_mtu = MTU512; break; case 1024: args.prot.ib_mtu = MTU1024; break; case 2048: args.prot.ib_mtu = MTU2048; break; case 4096: args.prot.ib_mtu = MTU4096; break; default: fprintf(stderr, "Invalid MTU size, must be one of " "256, 512, 1024, 2048, 4096\n"); exit(-1); } break; case 't': if( !strcmp(optarg, "send_recv") ) { printf("Using Send/Receive communications\n"); args.prot.commtype = NP_COMM_SENDRECV; } else if( !strcmp(optarg, "send_recv_with_imm") ) { printf("Using Send/Receive communications with immediate data\n"); args.prot.commtype = NP_COMM_SENDRECV_WITH_IMM; } else if( !strcmp(optarg, "rdma_write") ) { printf("Using RDMA Write communications\n"); args.prot.commtype = NP_COMM_RDMAWRITE; } else if( !strcmp(optarg, "rdma_write_with_imm") ) { printf("Using RDMA Write communications with immediate data\n"); args.prot.commtype = NP_COMM_RDMAWRITE_WITH_IMM; } else { fprintf(stderr, "Invalid transfer type " "specified, please choose one of:\n\n" "\tsend_recv\t\tUse Send/Receive communications\t(default)\n" "\tsend_recv_with_imm\tSame as above with immediate data\n" "\trdma_write\t\tUse RDMA Write communications\n" "\trdma_write_with_imm\tSame as above with immediate data\n\n"); exit(-1); } break; case 'c': if( !strcmp(optarg, "local_poll") ) { printf("Using local polling completion\n"); args.prot.comptype = NP_COMP_LOCALPOLL; } else if( !strcmp(optarg, "vapi_poll") ) { printf("Using VAPI polling completion\n"); args.prot.comptype = NP_COMP_VAPIPOLL; } else if( !strcmp(optarg, "event") ) { printf("Using VAPI event completion\n"); args.prot.comptype = NP_COMP_EVENT; } else { fprintf(stderr, "Invalid completion type specified, " "please choose one of:\n\n" "\tlocal_poll\tWait for last byte of data\t(default)\n" "\tvapi_poll\tUse VAPI polling function\n" "\tevent\t\tUse VAPI event handling function\n\n"); exit(-1); } break; #endif case 'n': nrepeat_const = atoi(optarg); break; #if defined(TCP) && ! defined(INFINIBAND) case 'r': args.reset_conn = 1; printf("Resetting connection after every trial\n"); break; #endif case 'P': args.port = atoi(optarg); break; default: PrintUsage(); exit(-12); } } #endif /* ! defined TCGMSG */ #if defined(INFINIBAND) asyncReceive = 1; fprintf(stderr, "Preposting asynchronous receives (required for Infiniband)\n"); if(args.bidir && ( (args.cache && args.prot.commtype == NP_COMM_RDMAWRITE) || /* rdma_write only works with no-cache mode */ (!args.preburst && args.prot.commtype != NP_COMM_RDMAWRITE) || /* anything besides rdma_write requires prepost burst */ (args.preburst && args.prot.comptype == NP_COMP_LOCALPOLL && args.cache) || /* preburst with local polling in cache mode doesn't work */ 0)) { fprintf(stderr, "\n" "Bi-directional mode currently only works with a subset of the\n" "Infiniband options. Restrictions are:\n" "\n" " RDMA write (-t rdma_write) requires no-cache mode (-I).\n" "\n" " Local polling (-c local_poll, default if no -c given) requires\n" " no-cache mode (-I), and if not using RDMA write communication,\n" " burst mode (-B).\n" "\n" " Any other communication type and any other completion type\n" " require burst mode (-B). No-cache mode (-I) may be used\n" " optionally.\n" "\n" " All other option combinations will fail.\n" "\n"); exit(-1); } #endif if (start > end) { fprintf(stderr, "Start MUST be LESS than end\n"); exit(420132); } args.nbuff = TRIALS; Setup(&args); if( args.bidir && end > args.upper ) { end = args.upper; if( args.tr ) { printf("The upper limit is being set to %d Bytes\n", end); #if defined(TCP) && ! defined(INFINIBAND) printf("due to socket buffer size limitations\n\n"); #endif } } #if defined(GM) if(streamopt && (!nrepeat_const || nrepeat_const > args.prot.num_stokens)) { printf("\nGM is currently limited by the driver software to %d\n", args.prot.num_stokens); printf("outstanding sends. The number of repeats will be set\n"); printf("to this limit for every trial in streaming mode. You\n"); printf("may use the -n switch to set a smaller number of repeats\n\n"); nrepeat_const = args.prot.num_stokens; } #endif if( args.tr ) /* Primary transmitter */ { if ((out = fopen(s, "w")) == NULL) { fprintf(stderr,"Can't open %s for output\n", s); exit(1); } } else out = stdout; /* Set a starting value for the message size increment. */ inc = (start > 1) ? start / 2 : 1; nq = (start > 1) ? 1 : 0; /* Test the timing to set tlast for the first test */ args.bufflen = start; MyMalloc(&args, args.bufflen, 0, 0); InitBufferData(&args, args.bufflen, 0, 0); if(args.cache) args.s_buff = args.r_buff; args.r_ptr = args.r_buff_orig = args.r_buff; args.s_ptr = args.s_buff_orig = args.s_buff; AfterAlignmentInit(&args); /* MPI-2 needs this to create a window */ /* Infiniband requires use of asynchronous communications, so we need * the PrepareToReceive calls below */ if( asyncReceive ) PrepareToReceive(&args); Sync(&args); /* Sync to prevent race condition in armci module */ /* For simplicity's sake, even if the real test below will be done in * bi-directional mode, we still do the ping-pong one-way-at-a-time test * here to estimate the one-way latency. Unless it takes significantly * longer to send data in both directions at once than it does to send data * one way at a time, this shouldn't be too far off anyway. */ t0 = When(); for( n=0; n<100; n++) { if( args.tr) { SendData(&args); RecvData(&args); if( asyncReceive && n<99 ) PrepareToReceive(&args); } else if( args.rcv) { RecvData(&args); if( asyncReceive && n<99 ) PrepareToReceive(&args); SendData(&args); } } tlast = (When() - t0)/200; /* Sync up and Reset before freeing the buffers */ Sync(&args); Reset(&args); /* Free the buffers and any other module-specific resources. */ if(args.cache) FreeBuff(args.r_buff_orig, NULL); else FreeBuff(args.r_buff_orig, args.s_buff_orig); /* Do setup for no-cache mode, using two distinct buffers. */ if (!args.cache) { /* Allocate dummy pool of memory to flush cache with */ if ( (memcache = (int *)malloc(MEMSIZE)) == NULL) { perror("malloc"); exit(1); } mymemset(memcache, 0, MEMSIZE/sizeof(int)); /* Allocate large memory pools */ MyMalloc(&args, MEMSIZE+bufalign, args.soffset, args.roffset); /* Save buffer addresses */ args.s_buff_orig = args.s_buff; args.r_buff_orig = args.r_buff; /* Align buffers */ args.s_buff = AlignBuffer(args.s_buff, bufalign); args.r_buff = AlignBuffer(args.r_buff, bufalign); /* Post alignment initialization */ AfterAlignmentInit(&args); /* Initialize send buffer pointer */ /* both soffset and roffset should be zero if we don't have any offset stuff, so this should be fine */ args.s_ptr = args.s_buff+args.soffset; args.r_ptr = args.r_buff+args.roffset; } /************************** * Main loop of benchmark * **************************/ if( args.tr ) fprintf(stderr,"Now starting the main loop\n"); for ( n = 0, len = start, errFlag = 0; n < NSAMP - 3 && tlast < STOPTM && len <= end && !errFlag; len = len + inc, nq++ ) { /* Exponentially increase the block size. */ if (nq > 2) inc = ((nq % 2))? inc + inc: inc; /* This is a perturbation loop to test nearby values */ for (pert = ((perturbation > 0) && (inc > perturbation+1)) ? -perturbation : 0; pert <= perturbation; n++, pert += ((perturbation > 0) && (inc > perturbation+1)) ? perturbation : perturbation+1) { Sync(&args); /* Sync to prevent race condition in armci module */ /* Calculate how many times to repeat the experiment. */ if( args.tr ) { if (nrepeat_const) { nrepeat = nrepeat_const; /* } else if (len == start) {*/ /* nrepeat = MAX( RUNTM/( 0.000020 + start/(8*1000) ), TRIALS);*/ } else { nrepeat = MAX((RUNTM / ((double)args.bufflen / (args.bufflen - inc + 1.0) * tlast)),TRIALS); } SendRepeat(&args, nrepeat); } else if( args.rcv ) { RecvRepeat(&args, &nrepeat); } args.bufflen = len + pert; if( args.tr ) fprintf(stderr,"%3d: %7d bytes %6d times --> ", n,args.bufflen,nrepeat); if (args.cache) /* Allow cache effects. We use only one buffer */ { /* Allocate the buffer with room for alignment*/ MyMalloc(&args, args.bufflen+bufalign, args.soffset, args.roffset); /* Save buffer address */ args.r_buff_orig = args.r_buff; args.s_buff_orig = args.r_buff; /* Align buffer */ args.r_buff = AlignBuffer(args.r_buff, bufalign); args.s_buff = args.r_buff; /* Initialize buffer with data * * NOTE: The buffers should be initialized with some sort of * valid data, whether it is actually used for anything else, * to get accurate results. Performance increases noticeably * if the buffers are left uninitialized, but this does not * give very useful results as realworld apps tend to actually * have data stored in memory. We are not sure what causes * the difference in performance at this time. */ InitBufferData(&args, args.bufflen, args.soffset, args.roffset); /* Post-alignment initialization */ AfterAlignmentInit(&args); /* Initialize buffer pointers (We use r_ptr and s_ptr for * compatibility with no-cache mode, as this makes the code * simpler) */ /* offsets are zero by default so this saves an #ifdef */ args.r_ptr = args.r_buff+args.roffset; args.s_ptr = args.r_buff+args.soffset; } else /* Eliminate cache effects. We use two distinct buffers */ { /* this isn't truly set up for offsets yet */ /* Size of an aligned memory block including trailing padding */ len_buf_align = args.bufflen; if(bufalign != 0) len_buf_align += bufalign - args.bufflen % bufalign; /* Initialize the buffers with data * * See NOTE above. */ InitBufferData(&args, MEMSIZE, args.soffset, args.roffset); /* Reset buffer pointers to beginning of pools */ args.r_ptr = args.r_buff+args.roffset; args.s_ptr = args.s_buff+args.soffset; } bwdata[n].t = LONGTIME; /* t2 = t1 = 0;*/ /* Finally, we get to transmit or receive and time */ /* NOTE: If a module is running that uses only one process (e.g. * memcpy), we assume that it will always have the args.tr flag * set. Thus we make some special allowances in the transmit * section that are not in the receive section. */ if( args.tr || args.bidir ) { /* This is the transmitter: send the block TRIALS times, and if we are not streaming, expect the receiver to return each block. */ for (i = 0; i < (integCheck ? 1 : TRIALS); i++) { if(args.preburst && asyncReceive && !streamopt) { /* We need to save the value of the recv ptr so * we can reset it after we do the preposts, in case * the module needs to use the same ptr values again * so it can wait on the last byte to change to indicate * the recv is finished. */ SaveRecvPtr(&args); for(j=0; j<nrepeat; j++) { PrepareToReceive(&args); if(!args.cache) AdvanceRecvPtr(&args, len_buf_align); } ResetRecvPtr(&args); } /* Flush the cache using the dummy buffer */ if (!args.cache) flushcache(memcache, MEMSIZE/sizeof(int)); Sync(&args); t0 = When(); for (j = 0; j < nrepeat; j++) { if (!args.preburst && asyncReceive && !streamopt) { PrepareToReceive(&args); } if (integCheck) SetIntegrityData(&args); SendData(&args); if (!streamopt) { RecvData(&args); if (integCheck) VerifyIntegrity(&args); if(!args.cache) AdvanceRecvPtr(&args, len_buf_align); } /* Wait to advance send pointer in case RecvData uses * it (e.g. memcpy module). */ if (!args.cache) AdvanceSendPtr(&args, len_buf_align); } /* t is the 1-directional trasmission time */ t = (When() - t0)/ nrepeat; if( !streamopt && !args.bidir) t /= 2; /* Normal ping-pong */ Reset(&args); /* NOTE: NetPIPE does each data point TRIALS times, bouncing the message * nrepeats times for each trial, then reports the lowest of the TRIALS * times. -Dave Turner */ bwdata[n].t = MIN(bwdata[n].t, t); /* t1 += t;*/ /* t2 += t*t;*/ } if (streamopt){ /* Get time info from Recv node */ RecvTime(&args, &bwdata[n].t); /* RecvTime(&args, &t1);*/ /* RecvTime(&args, &t2);*/ } /* Calculate variance after completing this set of trials */ /* bwdata[n].variance = t2/TRIALS - t1/TRIALS * t1/TRIALS;*/ } else if( args.rcv ) { /* This is the receiver: receive the block TRIALS times, and if we are not streaming, send the block back to the sender. */ for (i = 0; i < (integCheck ? 1 : TRIALS); i++) { if (asyncReceive) { if (args.preburst) { /* We need to save the value of the recv ptr so * we can reset it after we do the preposts, in case * the module needs to use the same ptr values again * so it can wait on the last byte to change to * indicate the recv is finished. */ SaveRecvPtr(&args); for (j=0; j < nrepeat; j++) { PrepareToReceive(&args); if (!args.cache) AdvanceRecvPtr(&args, len_buf_align); } ResetRecvPtr(&args); } else { PrepareToReceive(&args); } } /* Flush the cache using the dummy buffer */ if (!args.cache) flushcache(memcache, MEMSIZE/sizeof(int)); Sync(&args); t0 = When(); for (j = 0; j < nrepeat; j++) { RecvData(&args); if (integCheck) VerifyIntegrity(&args); if (!args.cache) { AdvanceRecvPtr(&args, len_buf_align); } if (!args.preburst && asyncReceive && (j < nrepeat-1)) { PrepareToReceive(&args); } if (!streamopt) { if (integCheck) SetIntegrityData(&args); SendData(&args); if(!args.cache) AdvanceSendPtr(&args, len_buf_align); } } t = (When() - t0)/ nrepeat; if( !streamopt && !args.bidir) t /= 2; /* Normal ping-pong */ Reset(&args); bwdata[n].t = MIN(bwdata[n].t, t); /* t1 += t;*/ /* t2 += t*t;*/ } if (streamopt){ /* Recv proc calcs time and sends to Trans */ SendTime(&args, &bwdata[n].t); /* SendTime(&args, &t1);*/ /* SendTime(&args, &t2);*/ } } else /* Just going along for the ride */ { for (i = 0; i < (integCheck ? 1 : TRIALS); i++) { Sync(&args); } } /* Streaming mode doesn't really calculate correct latencies * for small message sizes, and on some nics we can get * zero second latency after doing the math. Protect against * this. */ if(bwdata[n].t == 0.0) { bwdata[n].t = 0.000001; } tlast = bwdata[n].t; bwdata[n].bits = args.bufflen * CHARSIZE * (1+args.bidir); bwdata[n].bps = bwdata[n].bits / (bwdata[n].t * 1024 * 1024); bwdata[n].repeat = nrepeat; if (args.tr) { if(integCheck) { fprintf(out,"%8d %d", bwdata[n].bits / 8, nrepeat); } else { fprintf(out,"%8d %lf %12.8lf", bwdata[n].bits / 8, bwdata[n].bps, bwdata[n].t); } fprintf(out, "\n"); fflush(out); } /* Free using original buffer addresses since we may have aligned r_buff and s_buff */ if (args.cache) FreeBuff(args.r_buff_orig, NULL); if ( args.tr ) { if(integCheck) { fprintf(stderr, " Integrity check passed\n"); } else { fprintf(stderr," %8.2lf Mbps in %10.2lf usec\n", bwdata[n].bps, tlast*1.0e6); } } } /* End of perturbation loop */ } /* End of main loop */ /* Free using original buffer addresses since we may have aligned r_buff and s_buff */ if (!args.cache) { FreeBuff(args.s_buff_orig, args.r_buff_orig); } if (args.tr) fclose(out); CleanUp(&args); return 0; }
int main() { // start with a block header struct block_header header; // we need a place to store the checksums unsigned char hash1[SHA256_DIGEST_SIZE]; unsigned char hash2[SHA256_DIGEST_SIZE]; // you should be able to reuse these, but openssl sha256 is slow, so your probbally not going to implement this anyway sha256_ctx sha256_pass1, sha256_pass2; // we are going to supply the block header with the values from the generation block 0 header.version = 2; hex2bin(header.prev_block, "000000000000000117c80378b8da0e33559b5997f2ad55e2f7d18ec1975b9717"); hex2bin(header.merkle_root, "871714dcbae6c8193a2bb9b2a69fe1c0440399f38d94b3a0f1b447275a29978a"); header.timestamp = 1392872245; header.bits = 419520339; header.nonce = 0; // the endianess of the checksums needs to be little, this swaps them form the big endian format you normally see in block explorer byte_swap(header.prev_block, 32); // we need this to set up the header byte_swap(header.merkle_root, 32); // we need this to set up the header // dump out some debug data to the terminal printf("sizeof(block_header) = %d\n", sizeof(block_header)); printf("Block header (in human readable hexadecimal representation): "); hexdump((unsigned char*)&header, sizeof(block_header)); double start = When(); double timer = When() - start; while ( timer < 60.0){ // Use SSL's sha256 functions, it needs to be initialized sha256_init(&sha256_pass1); // then you 'can' feed data to it in chuncks, but here were just making one pass cause the data is so small sha256_update(&sha256_pass1, (unsigned char*)&header, sizeof(block_header)); // this ends the sha256 session and writes the checksum to hash1 sha256_final(hash1, &sha256_pass1); // to display this, we want to swap the byte order to big endian // byte_swap(hash1, SHA256_DIGEST_LENGTH); // this is for printing // printf("Useless First Pass Checksum: "); // hexdump(hash1, SHA256_DIGEST_LENGTH); // but to calculate the checksum again, we need it in little endian, so swap it back // byte_swap(hash1, SHA256_DIGEST_LENGTH); //same as above sha256_init(&sha256_pass2); sha256_update(&sha256_pass2, hash1, SHA256_DIGEST_SIZE); sha256_final(hash2, &sha256_pass2); if ( header.nonce == 0 || header.nonce == 3 || header.nonce == 856192328 ) { byte_swap(hash2, SHA256_DIGEST_SIZE); printf("Target Second Pass Checksum: "); hexdump(hash2, SHA256_DIGEST_SIZE); } header.nonce ++; if ( header.nonce % 800000 == 0){ timer = (When() - start); } } printf("number of hashs per second = %f\n",header.nonce / 60.0 ); return 0; }
int main(int argc, char * argv[]) { int nproc, iproc; MPI_Status status; MPI_Init(&argc, &argv); int i = 0; double starttime; /*All for the sending / recieving */ int* pivot=(int*)malloc(sizeof(int)); int* send=(int*)malloc(sizeof(int)); int* recv=(int*)malloc(sizeof(int)); MPI_Comm_size(MPI_COMM_WORLD, &nproc); MPI_Comm_rank(MPI_COMM_WORLD, &iproc); int mySize=SIZE/nproc; //my values int* vals = (int*)malloc( SIZE * sizeof(int)); //for holding their values that come in int* theirs = (int*)malloc( SIZE * sizeof(int)); //for joining the two and int* tmp = (int*)malloc( SIZE * sizeof(int)); //sort our values qsort(vals, mySize, sizeof(int), sort); for (i=0; i<mySize; i++) vals[i]=arc4random(); /*Create the communicator for use throughout*/ MPI_Comm newcomm; MPI_Comm_split(MPI_COMM_WORLD, 1, iproc, &newcomm); int groupSize=nproc; starttime = When(); while (groupSize>1) { /* Get the new rank/size */ MPI_Comm_size(newcomm, &nproc); MPI_Comm_rank(newcomm, &iproc); //Find the Pivot *pivot=getPivot(vals, mySize); if(1){ //send it out among the group MPI_Bcast(pivot, 1, MPI_INT, 0, newcomm); } else{ //median of all in group if(iproc==0){ //we recieve them all for (i=1; i<nproc; i++) { MPI_Recv(recv, 1, MPI_INT, i, 0, newcomm, &status); tmp[i]=*recv; } tmp[0]=*pivot; qsort(tmp, nproc, sizeof(int), sort); *pivot=tmp[(nproc/2)]; //fprintf(stderr, "pivot=%i\n",*pivot); for (i=1; i<nproc; i++) { MPI_Send(pivot, 1, MPI_INT, i, 0, newcomm); } } else{ //we all send it to zero and let it decide. MPI_Send(pivot, 1, MPI_INT, 0, 0, newcomm); MPI_Recv(pivot, 1, MPI_INT, 0, 0, newcomm, &status); } } //calculate how many we will send *send=0; for (i=0; i<mySize; i++) { if(iproc < nproc / 2){ if (vals[i] >= *pivot) { tmp[*send]=vals[i]; (*send)++; } } else{ if (vals[i] <= *pivot) { tmp[*send]=vals[i]; (*send)++; } } } //smalls send first if(iproc < nproc/2){ //send the size then the values //fprintf(stderr,"\t\t\t%d: sending %d to %d\n", iproc, *send, iproc+(nproc/2)); MPI_Send(send, 1, MPI_INT, iproc+(nproc/2), 0, newcomm); MPI_Send(tmp, *send, MPI_INT, iproc+(nproc/2), 0, newcomm); //we recieve the two MPI_Recv(recv, 1, MPI_INT, iproc+(nproc/2), 0, newcomm, &status); //fprintf(stderr,"\t\t\t\t%d: reciving %d from %d\n", iproc, *recv, iproc+(nproc/2)); MPI_Recv(theirs, *recv, MPI_INT, iproc+(nproc/2), 0, newcomm, &status); } else { //we recieve the two MPI_Recv(recv, 1, MPI_INT, iproc-(nproc/2), 0, newcomm, &status); //fprintf(stderr,"\t\t\t\t%d: reciving %d from %d\n", iproc, *recv, iproc-(nproc/2)); MPI_Recv(theirs, *recv, MPI_INT, iproc-(nproc/2), 0, newcomm, &status); //send the size then the values //fprintf(stderr,"\t\t\t%d: sending %d to %d\n", iproc, *send, iproc-(nproc/2)); MPI_Send(send, 1, MPI_INT, iproc-(nproc/2), 0, newcomm); MPI_Send(tmp, *send, MPI_INT, iproc-(nproc/2), 0, newcomm); } //now we combine the theirs and what is left of ours. if(iproc<nproc/2){ mySize-=*send; for (i=0; i<*recv; i++) { vals[mySize]=theirs[i]; mySize++; } } else{ int off=0; for (i=0; i<mySize; i++) { if(vals[i]>= *pivot){ theirs[*recv+off]=vals[i]; off++; } } int* temp=vals; vals=theirs; theirs=temp; mySize=*recv+(mySize-*send); } //fprintf(stderr,"%d:my size:%i,\n",iproc, mySize); qsort(vals, mySize, sizeof(int), sort); //reset the size of the group MPI_Comm_split(newcomm, iproc < nproc/2 , iproc, &newcomm); groupSize /= 2; } MPI_Comm_rank(MPI_COMM_WORLD, &iproc); fprintf(stderr,"\n%d:done: %f elements: %i\n", iproc, (When()-starttime),mySize); free(vals); free(theirs); free(tmp); free(send); free(recv); MPI_Finalize(); return 0; }
int main(int argc, char* argv[]) { double starttime, finishtime, runtime; float* ptrFrom, *ptrTo; float* tempPtr; float* flFrom, *flTo; int rowStart, i, j, start, roof; float total, self; int nproc, iproc; int steadyState, iterCount, cells50; int sendInt, receiveInt; MPI_Request req1, req2; MPI_Status stat1, stat2; //float arrFrom[NUM_ROWS * NUM_COLS]; //float arrTo[NUM_ROWS * NUM_COLS]; float bufSend[NUM_COLS]; float bufRecv[NUM_COLS]; starttime = When(); // putting these on the stack murders mpirun //ptrFrom = &arrFrom[0]; //ptrTo = &arrTo[0]; ptrFrom = (float*)malloc(NUM_ROWS * NUM_COLS * sizeof(float)); ptrTo = (float*)malloc(NUM_ROWS * NUM_COLS * sizeof(float)); initArrays(ptrFrom,ptrTo); steadyState = 0; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nproc); MPI_Comm_rank(MPI_COMM_WORLD, &iproc); start = ((float)NUM_ROWS / (float)nproc) * (float)iproc; // NUM_ROWS / numThreads is size of chunk work roof = start + ((float)NUM_ROWS / (float)nproc); //fprintf(stderr,"Proc(%d) Start: %d, Roof: %d\n", iproc, start, roof); if (start <= 0) // skip first row start = 1; if (roof >= NUM_ROWS) // skip last row roof = NUM_ROWS - 1; //fprintf(stderr,"Proc(%d) Revised - Start: %d, Roof: %d\n", iproc, start, roof); while (!steadyState) { steadyState = 1; if (start > 1) { rowStart = start * NUM_COLS; for (i = 0; i < NUM_COLS; i++) { bufSend[i] = ptrFrom[i + rowStart]; } MPI_Isend(&bufSend,NUM_COLS,MPI_FLOAT,iproc - 1,0,MPI_COMM_WORLD,&req1); MPI_Recv(&bufRecv,NUM_COLS,MPI_FLOAT,iproc - 1,0,MPI_COMM_WORLD,&stat1); rowStart -= NUM_COLS; for (i = 0; i < NUM_COLS; i++) { ptrFrom[i + rowStart] = bufRecv[i]; } } if (roof < (NUM_ROWS - 1)) { rowStart = (roof - 1) * NUM_COLS; // potential hazard here for algorithm correctness for (i = 0; i < NUM_COLS; i++) { bufSend[i] = ptrFrom[i + rowStart]; } MPI_Isend(&bufSend,NUM_COLS,MPI_FLOAT,iproc + 1,0,MPI_COMM_WORLD,&req2); MPI_Recv(&bufRecv,NUM_COLS,MPI_FLOAT,iproc + 1,0,MPI_COMM_WORLD,&stat2); rowStart += NUM_COLS; for (i = 0; i < NUM_COLS; i++) { ptrFrom[i + rowStart] = bufRecv[i]; } } for (i = start; i < roof; i++) { rowStart = i * NUM_COLS; flFrom = ptrFrom + rowStart; flTo = ptrTo + rowStart; //printf("I'm thread %ld, on row %d",t,i); for (j = 1; j < NUM_COLS - 1; j++) { if (*(flFrom + j) == 100) continue; total = *(flFrom - NUM_COLS + j) + *(flFrom + j-1) + *(flFrom + j+1) + *(flFrom + NUM_COLS + j); self = *(flFrom + j); *(flTo + j) = (total + 4 * self) / 8; if (steadyState && !(fabs(self - (total)/4) < 0.1)) steadyState = 0; } } //MPI_Reduce(); with min (because 0 is important, not 1) sendInt = steadyState; MPI_Allreduce ( &sendInt, &receiveInt, 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD); steadyState = receiveInt; iterCount++; tempPtr = ptrFrom; ptrFrom = ptrTo; ptrTo = tempPtr; } // my local count cells50 = 0; for (i = start; i < roof; i++) { flTo = ptrTo + i * NUM_COLS; for (j = 0; j < NUM_COLS; j++) { if (*(flTo + j) > 50) cells50++; } } sendInt = cells50; MPI_Allreduce ( &sendInt, &receiveInt, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); cells50 = receiveInt; if (iproc == 0) { finishtime = When(); runtime = finishtime - starttime; fprintf(stdout,"%d says:\n",iproc); fprintf(stdout,"Number of iterations: %d\n", iterCount); fprintf(stdout,"Time taken: %f\n", runtime); fprintf(stdout,"Number of cells w/ temp greater than 50: %d\n", cells50); } //pthread_exit(NULL); MPI_Finalize(); }
int main(int argc, char *argv[]) { // mpi book keeping ----------- int iproc, i, iter; int nproc; int number_amount; int membershipKey; int rank1,rank2,newSize; int rank; int numdim; int pivot; char host[255], message[55]; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nproc); MPI_Comm_rank(MPI_COMM_WORLD, &rank); gethostname(host,253); switch(nproc) { case 32: numdim = 5;break; case 16: numdim = 4;break; case 8: numdim = 3;break; case 4: numdim = 2;break; case 2: numdim = 1;break; case 1: numdim = 0;break; } // ------- // each process has an array of VECSIZE double: ain[VECSIZE] int ain[VECSIZE], *buf, *c = (int *) malloc(VECSIZE * sizeof(int)); int size = VECSIZE; int alower[2*VECSIZE], aupper[2*VECSIZE]; int myrank, root = 0; /* Intializes random number generator */ srand(rank+5); double start = When(); // Distribute the items evenly to all of the nodes. // fill with random numbers for(i = 0; i < VECSIZE; i++) { ain[i] = (rand()%1000)+1; // printf("init proc %d [%d]=%d\n",myrank,i,ain[i]); } memcpy(c,ain,sizeof(ain)); qsort(c, size, sizeof(int), cmpfunc); // Each node sorts the items it has using quicksort. MPI_Comm comm1 = MPI_COMM_WORLD, comm2, intercomm; rank2 = rank ; int lowerSize = 0 ,upperSize = 0; int *sub_avgs = NULL; for(int curdim = 0; curdim < numdim; curdim++ ) { membershipKey = rank2 % 2; // creates two groups o and 1. MPI_Comm_split(comm1, membershipKey, rank2, &comm2); // Break up the cube into two subcubes: MPI_Comm_rank(comm2,&rank2); if ( mediansPivot ){ // printf("meadians \n"); if (rank == 0 ){ sub_avgs =(int *) malloc(sizeof( int) * nproc); } pivot = median(size,c); // printf("before gather pivot = %ld\n",pivot); MPI_Gather(&pivot, 1, MPI_INT, sub_avgs, 1, MPI_INT, 0, MPI_COMM_WORLD); if ( rank == 0){ // for(int i=0; i<nproc; i++) // printf("[%d]=%ld ",i,sub_avgs[i]); // printf("Gathered\n"); pivot = median(nproc,sub_avgs); free(sub_avgs); } } else if ( rank2 == 0 && (medianPivot || meanPivot || randomPivot)){// Node 0 broadcasts its median key K to the rest of the cube. if (meanPivot ){ // printf("mean \n"); pivot = mean(size,c); } else if (medianPivot ){ // printf("meadian \n"); pivot = median(size,c); } else if (randomPivot ){ // printf("randomPivot \n"); int randompiv = rand()%size ; // printf("randomindex %d \n",randompiv ); pivot = c[randompiv]; // printf("Pivot %d \n", pivot); } } MPI_Bcast(&pivot,1,MPI_INT, 0, comm2); lowerSize = 0; upperSize = 0; for(i = 0; i < size; i++) {// Each node separates its items into two arrays : if (c[i] <= pivot){// keys <= K and alower[lowerSize] = c[i]; // printf("lower [%d]=%d\n",i,alower[lowerSize]); lowerSize ++; } else{// keys > K aupper[upperSize] = c[i]; // printf("upper [%d]=%d\n",i,aupper[upperSize]); upperSize ++; } } // printf("lowerSize %d\n",lowerSize); // printf("upperSize %d\n",upperSize); if (membershipKey == 0 ){ // lower world (left) MPI_Intercomm_create(comm2, 0, comm1, 1, 99, &intercomm); // Each node in the lower subcube sends its items whose keys are > K to its adjacent node in the upper subcube MPI_Send(aupper, upperSize, MPI_INT, rank2, 0, intercomm ); // printf("upperSize %ld ",upperSize); // printf("worldrank %d localrank %d sending upper\n ",rank, rank2); // for(i = 0; i < (upperSize); i++) // printf("[%d] = %ld ", i,aupper[i]); // printf("to otherrank %d \n ", rank2); MPI_Probe(rank2, 0, intercomm, &status); MPI_Get_count(&status, MPI_INT, &number_amount); buf = (int*)malloc(sizeof(int) * number_amount); MPI_Recv(buf, number_amount, MPI_INT, rank2, 0, intercomm, &status); free(buf); //Each node now merges together the group it just received // with the one it kept so that its items are one again sorted. free(c); c = ARRAY_CONCAT(int, alower, lowerSize, buf,number_amount); // printf("worldrank %d localrank %d gotsize %d\n",rank, rank2, number_amount); size = number_amount+lowerSize; /* for(i = 0; i < (number_amount); i++) printf("[%d]=%ld ",i,buf[i]); printf("\n "); for(i = 0; i < size; i++) printf("[%d]=%ld ",i,c[i]); printf("\n "); */ }else{
int main() { const std::complex<double> i(0.0,1.0); mch::var<double> a,b,r,f; mch::wildcard _; Match(i) { Qua(cartesian,a,b) std::cout << a << "+" << b << "*i" << std::endl; When(a,b |= a < b) std::cout << a << "<" << b << std::endl; When(a,b |= a ==b) std::cout << a << "==" << b << std::endl; When(a,b |= a > b) std::cout << a << ">" << b << std::endl; When(0,1) std::cout << "(0,1)" << std::endl; When(1+a,1+b) std::cout << "1+" << a << ",1+" << b << std::endl; When(a+1,b+1) std::cout << a << "+1," << b << "+1"<< std::endl; Qua(polar, r,f) std::cout << r << "*e^i" << f << std::endl; When(r,f |= r < f) std::cout << r << "<" << f << std::endl; When(r,f |= r ==f) std::cout << r << "==" << f << std::endl; When(r,f |= r > f) std::cout << r << ">" << f << std::endl; When(2*r,2*f) std::cout << "2*" << r << ",2*" << f << std::endl; When(r*2,f*2) std::cout << r << "*2," << f << "*2" << std::endl; When(r*2 |= r > 0.6,f*2) std::cout << r << "*2>1.2," << f << "*2" << std::endl; When(r*2,f*2 |= f > 0.6) std::cout << r << "*2," << f << "*2>1.2" << std::endl; When(r*2, _) std::cout << r << "*2, ???" << std::endl; //When(r*2, _ |= r < 0.6) std::cout << r << "*2<1.2, ???" << std::endl; When(r*2, f |= r < 0.6) std::cout << r << "*2<1.2, ???" << std::endl; // FIX: Replaced _ with f in the above as currently we don't have guard specialization } EndMatch }
void AxxTest_analogRead(int pin, int value){ When(Method(ArduinoHardwareMock, analogRead).Using(pin)).AlwaysReturn(value); }
void AxxTest_digitalRead(int pin, int state){ When(Method(ArduinoHardwareMock, digitalRead).Using(pin)).AlwaysReturn(state); }
void AxxTest_millis(uint32_t new_value){ fake_millis_value = new_value; When(Method(ArduinoHardwareMock, millis)).AlwaysReturn(new_value); }
main(int argc, char*argv[]) { int iproc, nproc, i, iter,done,reallydone,cnt; char host[255], message[55]; MPI_Status status; MPI_Init(&argc, &argv); double starttime = When(); MPI_Comm_size(MPI_COMM_WORLD, &nproc); MPI_Comm_rank(MPI_COMM_WORLD, &iproc); int numRow = SIZE/nproc; int numCol = SIZE; int row,col = 0; float *cur[numRow]; float *old[numRow]; float **temp,**currentplate,**oldplate; currentplate = cur; oldplate = old; for(row=0;row<numRow;row++) { cur[row] = (float *)malloc(numCol * sizeof(float)); old[row] = (float *)malloc(numCol * sizeof(float)); } float *above; above = (float *)malloc(numCol * sizeof(float)); float *below; below = (float *)malloc(numCol * sizeof(float)); for(row=0; row<numRow;row++) { for(col=0;col<numCol;col++) { oldplate[row][col]=50; currentplate[row][col] = 50; if(col==0 || col==numCol-1) { oldplate[row][col] =0; currentplate[row][col] = 0; } if(iproc== nproc-1 && row == numRow-1) { oldplate[row][col] = 100; currentplate[row][col]= 100; } if(iproc==0 && row== 0) { oldplate[row][col] = 0; currentplate[row][col] = 0; } } } printf("I am proc %d of %d\n",iproc,nproc); reallydone =0; float test = 5; for(cnt=0; !reallydone;cnt++) { //SENDS AND RECEIVES if(iproc!=0) { //Everyone but 0 send your first row up MPI_Send(oldplate[0],numCol,MPI_FLOAT, iproc-1,0,MPI_COMM_WORLD); } if(iproc!=nproc-1) { //Everyone but Last receive the row from below MPI_Recv(below,numCol,MPI_FLOAT,iproc+1,0,MPI_COMM_WORLD, &status); //Everyone but the Last send your bottom row down MPI_Send(oldplate[numRow-1],numCol,MPI_FLOAT, iproc+1,0,MPI_COMM_WORLD); } if(iproc!=0) { //Everyone but 0 reveive the row from above MPI_Recv(above,numCol,MPI_FLOAT,iproc-1,0,MPI_COMM_WORLD, &status); } //CALCULATIONS int start= 0; int end = numRow; if(iproc==0) start = 1; if(iproc==nproc-1) end = numRow-1; for(row =start;row<end;row++) { for(col=1;col<numCol-2;col++) { if(row == 0) currentplate[row][col] = (above[col]+oldplate[row+1][col]+oldplate[row][col+1]+oldplate[row][col-1]+(4*oldplate[row][col]))/8; else if(row==numRow-1) { currentplate[row][col] = (oldplate[row-1][col]+below[col]+oldplate[row][col+1]+oldplate[row][col-1]+(4*oldplate[row][col]) )/8; } else currentplate[row][col] = (oldplate[row+1][col]+oldplate[row-1][col]+oldplate[row][col+1]+oldplate[row][col-1]+(4*oldplate[row][col]) )/8; } } //CHECK TO SEE IF WE ARE DONE done = 1; start = 0; end = numRow; if(iproc==0) start = 1; if(iproc==nproc-1) end = numRow-1; for(row=start;row<numRow-2;row++) { if(done==0) break; for(col=1;col<numCol-2;col++) { if(row==0) { if(fabs(currentplate[row][col]-((currentplate[row+1][col]+above[col]+currentplate[row][col+1]+currentplate[row][col-1] )/4))> .1) { done=0; break; } } else if(row== numRow-1) { if(fabs(currentplate[row][col]-((above[col]+currentplate[row-1][col]+currentplate[row][col+1]+currentplate[row][col-1] )/4))> .1) { done=0; break; } } else if(fabs(currentplate[row][col]-((currentplate[row+1][col]+currentplate[row-1][col]+currentplate[row][col+1]+currentplate[row][col-1] )/4))> .1) { float dif = (currentplate[row][col]-((currentplate[row+1][col]+currentplate[row-1][col]+currentplate[row][col+1]+currentplate[row][col-1] ))/4); done=0; break; } } } MPI_Allreduce(&done, &reallydone, 1, MPI_INT,MPI_MIN,MPI_COMM_WORLD); temp = currentplate; currentplate = oldplate; oldplate = temp; } printf("%d: It took %d iterations and %lf seconds to relax the system\n",iproc,cnt,When()-starttime); MPI_Finalize(); }
int main(int argc, char *argv[]) { int i, j; //printf("argv[1]: %s\n", argv[1]); int numThreads = atoi(argv[1]); //printf("num of threads %d\n", numThreads); //omp_set_num_threads(numThreads); time_t start, end; clock_t ticks; long count; //create threads int nThreads = numThreads; pthread_t threads[nThreads]; long thread; time(&start); double begin = When(); float** hotplateOld = (float**)malloc(NUM_OF_ROWS*sizeof(float*)); for (i = 0; i < NUM_OF_ROWS; i++) { hotplateOld[i] = (float*)malloc(NUM_OF_COLS * sizeof(float)); } float** hotplateNew = (float**)malloc(NUM_OF_ROWS * sizeof(float*)); for (i = 0; i < NUM_OF_ROWS; i++) { hotplateNew[i] = (float*)malloc(NUM_OF_COLS * sizeof(float)); } float** temp = (float**)malloc(NUM_OF_ROWS * sizeof(float*)); for (i = 0; i < NUM_OF_ROWS; i++) { temp[i] = (float*)malloc(NUM_OF_COLS * sizeof(float)); } int range = NUM_OF_ROWS/nThreads; double beginInit = When(); for(thread=0;thread<nThreads;thread++) { int start = range * thread; int end = range * (thread+1); struct arg_struct *args = malloc(sizeof *args); args->hotOld = hotplateOld; args->hotNew = hotplateNew; args->start = start; args->end = end; pthread_create(&threads[thread], NULL, &initialize, args); } for(thread=0;thread<nThreads;thread++) { pthread_join(threads[thread], NULL); } double stopInit = When(); printf("Initialization time: %f seconds\n",stopInit-beginInit); //printf("%f", hotplateNew[0][0]); int numOfIterations = 0; bool stable; int numCells; //for(i=0;i<98;i++){ do { stable = true; numCells = 0; numOfIterations++; for(thread=0;thread<nThreads;thread++) { int start = range * thread; int end = range * (thread+1); struct arg_struct *args=malloc(sizeof *args); args->hotOld = hotplateOld; args->hotNew = hotplateNew; args->start = start; args->end = end; pthread_create(&threads[thread], NULL, &iterate,args); } for(thread=0;thread<nThreads;thread++) { pthread_join(threads[thread], NULL); } printf("iterations %d\n", numOfIterations); temp = hotplateOld; hotplateOld = hotplateNew; hotplateNew = temp; for(thread=0;thread<nThreads;thread++) { int start = range * thread; int end = range * (thread+1); //printf("start: %d\nend: %d\n", start,end); struct arg_struct *args=malloc(sizeof *args); args->hotOld = hotplateOld; args->hotNew = hotplateNew; args->start = start; args->end = end; pthread_create(&threads[thread], NULL, &isStable,args); } for(thread=0;thread<nThreads;thread++) { struct ret_struct *stat; pthread_join(threads[thread], (void*)&stat); numCells += stat->numCells; if(stat->isStable == false) { stable = false; } free(stat); } } while (!stable); time(&end); double stop = When(); printf("%d number of cells\n", numCells); printf("%d iterations\n", numOfIterations); //printf("%f seconds\n", difftime(end, start)); printf("%f seconds\n", stop-begin); return 0; }
virtual void Run(){ Given("a MockReturnHandler", [&]() { m_returner = ut11::detail::MockReturnHandler<int, char>(); }); When("calling the MockReturnHandler", [&]() { m_expectedReturnValue = ut11::utility::DefaultValue<int>()(); m_returnedValue = m_returner.operator ()('A'); }); Then("the return value is the expected value", [&]() { AssertThat(m_returnedValue, ut11::Is::EqualTo(m_expectedReturnValue)); }); When("setting the value to be returned and calling the MockReturnHandler", [&]() { m_expectedReturnValue = 32; m_returner.SetReturn(m_expectedReturnValue); m_returnedValue = m_returner.operator ()('A'); }); Then("the return value is the expected value", [&]() { AssertThat(m_returnedValue, ut11::Is::EqualTo(m_expectedReturnValue)); }); When("setting the a return function and calling the MockReturnHandler", [&]() { m_expectedReturnValue = 32; m_expectedArgument = 'Z'; m_returner.SetReturn([&](char actual) { m_actualArgument = actual; return m_expectedReturnValue; }); m_returnedValue = m_returner.operator ()(m_expectedArgument); }); Then("the return value is the expected value", [&]() { AssertThat(m_returnedValue, ut11::Is::EqualTo(m_expectedReturnValue)); }); Then("the argument passed in to the return function is the expected value", [&]() { AssertThat(m_actualArgument, ut11::Is::EqualTo(m_expectedArgument)); }); When("setting the a return value, overriding that with a return function and calling the MockReturnHandler", [&]() { m_expectedReturnValue = 32; m_expectedArgument = 'Z'; m_returner.SetReturn('A'); m_returner.SetReturn([&](char actual) { m_actualArgument = actual; return m_expectedReturnValue; }); m_returnedValue = m_returner.operator ()(m_expectedArgument); }); Then("the return value is the expected value", [&]() { AssertThat(m_returnedValue, ut11::Is::EqualTo(m_expectedReturnValue)); }); Then("the argument passed in to the return function is the expected value", [&]() { AssertThat(m_actualArgument, ut11::Is::EqualTo(m_expectedArgument)); }); When("setting the a return function, overriding that with a return value and calling the MockReturnHandler", [&]() { m_expectedReturnValue = 32; m_returner.SetReturn([&](char) { return 21; }); m_returner.SetReturn(m_expectedReturnValue); m_returnedValue = m_returner.operator ()(m_expectedArgument); }); Then("the return value is the expected value", [&]() { AssertThat(m_returnedValue, ut11::Is::EqualTo(m_expectedReturnValue)); }); }
int main(int argc, char** argv) { // mandelbrot int* pixels; int i, j; int color; // mpi int nproc, iproc; int* mySendArr; int* myRecvArr; MPI_Status status; // miscellaneous int loop; // used as boolean int loopCount; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nproc); MPI_Comm_rank(MPI_COMM_WORLD, &iproc); // everyone needs a send and a recv array // the extra 1 is for the start location mySendArr = (int*)malloc((BLOCK_WIDTH * BLOCK_HEIGHT + 1) * sizeof(int)); myRecvArr = (int*)malloc((BLOCK_WIDTH * BLOCK_HEIGHT + 1) * sizeof(int)); if (iproc == 0) { // master code int numJobs; int jobCount; int jobStart; double timestart, timefinish, timetaken; numJobs = NUM_JOBS; jobCount = 0; //fprintf(stderr,"(%d) I'm the master\n",iproc); pixels = (int*)malloc(WIDTH * HEIGHT * sizeof(int)); timestart = When(); /* for (j = 0; j < HEIGHT; j++) { for (i = 0; i < WIDTH; i++) { pixels[i + j * WIDTH] = computePoint(i, j); } } */ //loop = 1; for (loopCount = 0; loopCount < (NUM_JOBS * 2 + nproc - 1); loopCount++) { //fprintf(stderr,"(%d) I'm waiting\n",iproc); MPI_Recv(myRecvArr,1,MPI_INT,MPI_ANY_SOURCE,0,MPI_COMM_WORLD,&status); // fprintf(stderr,"(%d) %d sent me a message: %lf\n",iproc,status.MPI_SOURCE,myRecvArr[0]); if (myRecvArr[0] == -1) { // worker wants more work //fprintf(stderr,"(%d) %d wants more work\n",iproc,status.MPI_SOURCE); if (numJobs > 0) { // tell worker there is a job starting at numJobs - 1 * BLOCK_WIDTH mySendArr[0] = jobCount * BLOCK_WIDTH; jobCount++; MPI_Send(mySendArr,1,MPI_INT,status.MPI_SOURCE,0,MPI_COMM_WORLD); numJobs--; } else { // tell worker there isn't any more mySendArr[0] = -1; MPI_Send(mySendArr,1,MPI_INT,status.MPI_SOURCE,0,MPI_COMM_WORLD); } } else if (myRecvArr[0] == -2) { // worker wants to send finished work //fprintf(stderr,"(%d) %d wants to send me their work\n",iproc,status.MPI_SOURCE); MPI_Recv(myRecvArr,BLOCK_WIDTH * BLOCK_HEIGHT + 1,MPI_INT,status.MPI_SOURCE,0,MPI_COMM_WORLD,&status); // worker sent work with start number //fprintf(stderr,"(%d) %d sent me their work starting at %d\n",iproc,status.MPI_SOURCE,myRecvArr[0]); // copy work into pixel array jobStart = myRecvArr[0]; for (i = 1; i < BLOCK_WIDTH * BLOCK_HEIGHT + 1; i++) { pixels[i-1 + jobStart] = myRecvArr[i]; //fprintf(stderr,"%d ",pixels[i-1 + jobStart]); } } //loop = 0; } timefinish = When(); timetaken = timefinish - timestart; //fprintf(stderr,"(%d) I'm finished\n",iproc); fprintf(stdout,"(%d) Time taken: %lf\n",iproc,timetaken); fileWrite(pixels); free(pixels); } else { // worker code int myJobStart; //fprintf(stderr,"\t(%d) I'm a worker\n",iproc); pixels = (int*)malloc(BLOCK_WIDTH * BLOCK_HEIGHT * sizeof(int)); loop = 1; while (loop) { // ask master for work mySendArr[0] = -1; MPI_Send(mySendArr,1,MPI_INT,0,0,MPI_COMM_WORLD); // recv response (starting number or -1) MPI_Recv(myRecvArr,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); if (myRecvArr[0] == -1) { // -1 means no more //fprintf(stderr,"\t(%d) Master says no more work\n",iproc); loop = 0; } else { //fprintf(stderr,"\t(%d) Master gave me start of %d\n",iproc,myRecvArr[0]); myJobStart = myRecvArr[0]; // do work #pragma omp parallel for private(i, j) for (j = 0; j < BLOCK_HEIGHT; j++) { for (i = 0; i < BLOCK_WIDTH; i++) { pixels[i + j * BLOCK_WIDTH] = computePoint(i, j + myJobStart / 1536); //fprintf(stderr,"%d ",pixels[i + j * BLOCK_WIDTH]); } } // tell master work is done and ready to send mySendArr[0] = -2; MPI_Send(mySendArr,1,MPI_INT,0,0,MPI_COMM_WORLD); // send work mySendArr[0] = myJobStart; for (i = 1; i < BLOCK_WIDTH * BLOCK_HEIGHT + 1; i++) { mySendArr[i] = pixels[i-1]; } MPI_Send(mySendArr,BLOCK_WIDTH * BLOCK_HEIGHT + 1,MPI_INT,0,0,MPI_COMM_WORLD); } } //fprintf(stderr,"\t(%d) I'm finished\n",iproc); } MPI_Finalize(); return 0; }
void main(int argc, char *argv[]) { float *nA, *oA, *tmp; int i, done, reallydone; int cnt; int start, end; int theSize; double starttime; int nproc, iproc; MPI_Status status; MPI_Init(&argc, &argv); starttime = When(); MPI_Comm_size(MPI_COMM_WORLD, &nproc); MPI_Comm_rank(MPI_COMM_WORLD, &iproc); fprintf(stderr,"%d: Hello from %d of %d\n", iproc, iproc, nproc); /* Determine how much I should be doing and allocate the arrays*/ theSize = SIZE / nproc; nA = (float *)malloc((theSize + 2) * sizeof(float)); oA = (float *)malloc((theSize + 2) * sizeof(float)); start = 1; end = theSize + 1; /* Initialize the cells */ for (i = 0; i < theSize+2; i++) { nA[i] = oA[i] = 50; } /* Initialize the Boundaries */ if (iproc == 0) { start = 2; nA[1] = oA[1] = 100; } if (iproc == nproc - 1) { end = theSize; nA[theSize] = oA[theSize] = 0; } /* Now run the relaxation */ reallydone = 0; for(cnt = 0; !reallydone; cnt++) { /* First, I must get my neighbors boundary values */ if (iproc != 0) { MPI_Send(&oA[1], 1, MPI_FLOAT, iproc - 1, 0, MPI_COMM_WORLD); MPI_Recv(&oA[0], 1, MPI_FLOAT, iproc - 1, 0, MPI_COMM_WORLD, &status); } if (iproc != nproc - 1) { MPI_Send(&oA[theSize], 1, MPI_FLOAT, iproc + 1, 0, MPI_COMM_WORLD); MPI_Recv(&oA[theSize + 1], 1, MPI_FLOAT, iproc + 1, 0, MPI_COMM_WORLD, &status); } /* Do the calculations */ for (i = start; i < end; i++) { nA[i] = (oA[i-1] + oA[i+1] + 2 * oA[i]) / 4.0; } /* Check to see if we are done */ done = 1; for (i = start; i < end; i++) { if (fabs((nA[i-1] + nA[i+1])/ 2.0 - nA[i]) > EPSILON) { done = 0; break; } } /* Do a reduce to see if everybody is done */ MPI_Allreduce(&done, &reallydone, 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD); /* Swap the pointers */ tmp = nA; nA = oA; oA = tmp; } /* print out the number of iterations to relax */ fprintf(stderr, "%d:It took %d iterations and %lf seconds to relax the system\n", iproc,cnt,When() - starttime); MPI_Finalize(); }
int main(int argc, char *argv[]) { FILE *out; /* Output data file */ char s[255]; /* Generic string */ char *memtmp; char *memtmp1; int c, /* option index */ i, j, n, nq, /* Loop indices */ asyncReceive=0, /* Pre-post a receive buffer? */ bufoffset=0, /* Align buffer to this */ bufalign=16*1024,/* Boundary to align buffer to */ errFlag, /* Error occurred in inner testing loop */ nrepeat, /* Number of time to do the transmission */ len, /* Number of bytes to be transmitted */ inc=0, /* Increment value */ trans=-1, /* Transmitter flag. 1 if transmitting. */ detailflag=0, /* Set to examine the signature curve detail */ bufszflag=0, /* Set to change the TCP socket buffer size */ pert, /* Perturbation value */ start=1, /* Starting value for signature curve */ end=MAXINT, /* Ending value for signature curve */ streamopt=0, /* Streaming mode flag */ printopt=0; /* Debug print statements flag */ ArgStruct args; /* Argumentsfor all the calls */ double t, t0, t1, t2, /* Time variables */ tlast, /* Time for the last transmission */ latency; /* Network message latency */ Data bwdata[NSAMP]; /* Bandwidth curve data */ short port=DEFPORT; /* Port number for connection */ #ifdef HAVE_GETRUSAGE struct rusage prev_rusage, curr_rusage; /* Resource usage */ double user_time, sys_time; /* User & system time used */ double best_user_time, best_sys_time; /* Total user & system time used */ double ut1, ut2, st1, st2; /* User & system time ctrs for variance */ double ut_var, st_var; /* Variance in user & system time */ #endif #ifdef MPI MPI_Init(&argc, &argv); #endif strcpy(s, "NetPIPE.out"); #ifndef MPI if(argc < 2) PrintUsage(); #endif /* Parse the arguments. See Usage for description */ while ((c = getopt(argc, argv, "Pstrh:p:o:A:O:l:u:i:b:a")) != -1) { switch(c) { case 'o': strcpy(s,optarg); break; case 't': trans = 1; break; case 'r': trans = 0; break; case 's': streamopt = 1; break; case 'l': /*detailflag = 1;*/ start = atoi(optarg); if (start < 1) { fprintf(stderr,"Need a starting value >= 1\n"); exit(743); } break; case 'u': /*detailflag = 1;*/ end = atoi(optarg); break; case 'i': detailflag = 1; inc = atoi(optarg); break; case 'b': bufszflag = 1; #ifdef TCP args.prot.rcvbufsz=atoi(optarg); args.prot.sndbufsz=args.prot.rcvbufsz; #endif break; case 'P': printopt = 1; break; case 'A': bufalign = atoi(optarg); break; case 'O': bufoffset = atoi(optarg); break; case 'p': port = atoi(optarg); break; case 'h': if (trans == 1) { args.host = (char *)malloc(strlen(optarg)+1); strcpy(args.host, optarg); } else { fprintf(stderr, "Error: -t must be specified before -h\n"); exit(-11); } break; case 'a': asyncReceive = 1; break; default: PrintUsage(); exit(-12); } } if (start > end) { fprintf(stderr, "Start MUST be LESS than end\n"); exit(420132); } #if defined(TCP) || defined(PVM) /* It should be explicitly specified whether this is the transmitter or the receiver. */ if (trans < 0) { fprintf(stderr, "Error: either -t or -r must be specified\n"); exit(-11); } #endif args.nbuff = TRIALS; args.tr = trans; args.port = port; #if defined(TCP) if (!bufszflag) { args.prot.sndbufsz = 0; args.prot.rcvbufsz = 0; } else fprintf(stderr,"Send and Recv Buffers are %d bytes\n", args.prot.sndbufsz); #endif Setup(&args); Establish(&args); if (args.tr) { if ((out = fopen(s, "w")) == NULL) { fprintf(stderr,"Can't open %s for output\n", s); exit(1); } } else out = stdout; args.bufflen = 1; args.buff = (char *)malloc(args.bufflen); args.buff1 = (char *)malloc(args.bufflen); if (asyncReceive) PrepareToReceive(&args); Sync(&args); t0 = When(); t0 = When(); t0 = When(); #ifdef HAVE_GETRUSAGE getrusage(RUSAGE_SELF, &prev_rusage); #endif t0 = When(); for (i = 0; i < LATENCYREPS; i++) { if (args.tr) { SendData(&args); RecvData(&args); if (asyncReceive && (i < LATENCYREPS - 1)) { PrepareToReceive(&args); } } else { RecvData(&args); if (asyncReceive && (i < LATENCYREPS - 1)) { PrepareToReceive(&args); } SendData(&args); } } latency = (When() - t0)/(2 * LATENCYREPS); #ifdef HAVE_GETRUSAGE getrusage(RUSAGE_SELF, &curr_rusage); #endif free(args.buff); free(args.buff1); if (args.tr) { SendTime(&args, &latency); } else { RecvTime(&args, &latency); } if (args.tr && printopt) { fprintf(stderr,"Latency: %.7f\n", latency); fprintf(stderr,"Now starting main loop\n"); } tlast = latency; if (inc == 0) { /* Set a starting value for the message size increment. */ inc = (start > 1) ? start / 2 : 1; } /* Main loop of benchmark */ for (nq = n = 0, len = start, errFlag = 0; n < NSAMP - 3 && tlast < STOPTM && len <= end && !errFlag; len = len + inc, nq++ ) { if (nq > 2 && !detailflag) { /* This has the effect of exponentially increasing the block size. If detailflag is false, then the block size is linearly increased (the increment is not adjusted). */ inc = ((nq % 2))? inc + inc: inc; } /* This is a perturbation loop to test nearby values */ for (pert = (!detailflag && inc > PERT+1)? -PERT: 0; pert <= PERT; n++, pert += (!detailflag && inc > PERT+1)? PERT: PERT+1) { /* Calculate how many times to repeat the experiment. */ if (args.tr) { nrepeat = MAX((RUNTM / ((double)args.bufflen / (args.bufflen - inc + 1.0) * tlast)), TRIALS); SendRepeat(&args, nrepeat); } else { RecvRepeat(&args, &nrepeat); } /* Allocate the buffer */ args.bufflen = len + pert; if((args.buff=(char *)malloc(args.bufflen+bufalign))==(char *)NULL) { fprintf(stderr,"Couldn't allocate memory\n"); errFlag = -1; break; } if((args.buff1=(char *)malloc(args.bufflen+bufalign))==(char *)NULL) { fprintf(stderr,"Couldn't allocate memory\n"); errFlag = -1; break; } /* Possibly align the data buffer: make memtmp and memtmp1 point to the original blocks (so they can be freed later), then adjust args.buff and args.buff1 if the user requested it. */ memtmp = args.buff; memtmp1 = args.buff1; if (bufalign != 0) args.buff +=(bufalign - ((int)(*args.buff) % bufalign) + bufoffset) % bufalign; if (bufalign != 0) args.buff1 +=(bufalign - ((int)(*args.buff1) % bufalign) + bufoffset) % bufalign; if (args.tr && printopt) fprintf(stderr,"%3d: %9d bytes %4d times --> ", n,args.bufflen,nrepeat); /* Finally, we get to transmit or receive and time */ if (args.tr) { /* This is the transmitter: send the block TRIALS times, and if we are not streaming, expect the receiver to return each block. */ bwdata[n].t = LONGTIME; t2 = t1 = 0; #ifdef HAVE_GETRUSAGE ut1 = ut2 = st1 = st2 = 0.0; best_user_time = best_sys_time = LONGTIME; #endif for (i = 0; i < TRIALS; i++) { Sync(&args); #ifdef HAVE_GETRUSAGE getrusage(RUSAGE_SELF, &prev_rusage); #endif t0 = When(); for (j = 0; j < nrepeat; j++) { if (asyncReceive && !streamopt) { PrepareToReceive(&args); } SendData(&args); if (!streamopt) { RecvData(&args); } } t = (When() - t0)/((1 + !streamopt) * nrepeat); #ifdef HAVE_GETRUSAGE getrusage(RUSAGE_SELF, &curr_rusage); user_time = ((curr_rusage.ru_utime.tv_sec - prev_rusage.ru_utime.tv_sec) + (double) (curr_rusage.ru_utime.tv_usec - prev_rusage.ru_utime.tv_usec) * 1.0E-6) / ((1 + !streamopt) * nrepeat); sys_time = ((curr_rusage.ru_stime.tv_sec - prev_rusage.ru_stime.tv_sec) + (double) (curr_rusage.ru_stime.tv_usec - prev_rusage.ru_stime.tv_usec) * 1.0E-6) / ((1 + !streamopt) * nrepeat); ut2 += user_time * user_time; st2 += sys_time * sys_time; ut1 += user_time; st1 += sys_time; if ((user_time + sys_time) < (best_user_time + best_sys_time)) { best_user_time = user_time; best_sys_time = sys_time; } #endif if (!streamopt) { t2 += t*t; t1 += t; bwdata[n].t = MIN(bwdata[n].t, t); } } if (!streamopt) SendTime(&args, &bwdata[n].t); else RecvTime(&args, &bwdata[n].t); if (!streamopt) bwdata[n].variance = t2/TRIALS - t1/TRIALS * t1/TRIALS; #ifdef HAVE_GETRUSAGE ut_var = ut2/TRIALS - (ut1/TRIALS) * (ut1/TRIALS); st_var = st2/TRIALS - (st1/TRIALS) * (st1/TRIALS); #endif } else { /* This is the receiver: receive the block TRIALS times, and if we are not streaming, send the block back to the sender. */ bwdata[n].t = LONGTIME; t2 = t1 = 0; for (i = 0; i < TRIALS; i++) { if (asyncReceive) { PrepareToReceive(&args); } Sync(&args); t0 = When(); for (j = 0; j < nrepeat; j++) { RecvData(&args); if (asyncReceive && (j < nrepeat - 1)) { PrepareToReceive(&args); } if (!streamopt) SendData(&args); } t = (When() - t0)/((1 + !streamopt) * nrepeat); if (streamopt) { t2 += t*t; t1 += t; bwdata[n].t = MIN(bwdata[n].t, t); } } if (streamopt) SendTime(&args, &bwdata[n].t); else RecvTime(&args, &bwdata[n].t); if (streamopt) bwdata[n].variance = t2/TRIALS - t1/TRIALS * t1/TRIALS; } tlast = bwdata[n].t; bwdata[n].bits = args.bufflen * CHARSIZE; bwdata[n].bps = bwdata[n].bits / (bwdata[n].t * 1024 * 1024); bwdata[n].repeat = nrepeat; if (args.tr) { fprintf(out, "%.7f %.7f %d %d %.7f", bwdata[n].t, bwdata[n].bps, bwdata[n].bits, bwdata[n].bits / 8, bwdata[n].variance); #ifdef HAVE_GETRUSAGE fprintf(out, " %.7f %.7f %.7f %.7f", ut1 / (double) TRIALS, st1 / (double) TRIALS, ut_var, st_var); #endif fprintf(out, "\n"); } fflush(out); free(memtmp); free(memtmp1); if (args.tr && printopt) { fprintf(stderr," %6.2f Mbps in %.7f sec", bwdata[n].bps, tlast); #ifdef HAVE_GETRUSAGE fprintf(stderr, ", avg utime=%.7f avg stime=%.7f, ", ut1 / (double) TRIALS, st1 / (double) TRIALS); fprintf(stderr, "min utime=%.7f stime=%.7f, ", best_user_time, best_sys_time); fprintf(stderr, "utime var=%.7f stime var=%.7f", ut_var, st_var); #endif fprintf(stderr, "\n"); } } /* End of perturbation loop */ } /* End of main loop */ if (args.tr) fclose(out); CleanUp(&args); return(0); }
int main(int argc, char *argv[]) { setbuf(stdout, 0); float **plate, **prev_plate, **temp_plate, **locked_cells; int start, end, rows_assinged; MPI_Init(&argc, &argv); char host[255]; gethostname(host,253); int nproc, iproc; MPI_Status status; MPI_Request request; MPI_Comm_size(MPI_COMM_WORLD, &nproc); MPI_Comm_rank(MPI_COMM_WORLD, &iproc); printf("I am process rank %d of %d running on %s\n", iproc, nproc,host); /* Determine how much I should be doing and allocate the arrays*/ rows_assinged = SIZE / nproc; // rows for a specific processor to look at plate = createPlate(rows_assinged); prev_plate = createPlate(rows_assinged); locked_cells = createPlate(rows_assinged); start = 1; end = rows_assinged + 1; /* Initialize the cells */ initPlate(plate, prev_plate, locked_cells, rows_assinged, iproc); if (iproc == 0) { start = 2; } if (iproc == (nproc - 1)) { end = rows_assinged; } /* First we need to get the 0th row of locked cells from my previous neighbor */ if (iproc != 0) { MPI_Isend(locked_cells[1], SIZE, MPI_FLOAT, iproc - 1, 0, MPI_COMM_WORLD, &request); MPI_Recv(locked_cells[0], SIZE, MPI_FLOAT, iproc - 1, 0, MPI_COMM_WORLD, &status); } if (iproc != (nproc - 1)) { MPI_Isend(locked_cells[rows_assinged], SIZE, MPI_FLOAT, iproc + 1, 0, MPI_COMM_WORLD, &request); MPI_Recv(locked_cells[rows_assinged + 1], SIZE, MPI_FLOAT, iproc + 1, 0, MPI_COMM_WORLD, &status); } /* Now run the relaxation */ double starttime = When(); int done = 0, reallydone = 0, iterations = 0; while(!reallydone) { iterations++; /* First, I must get my neighbors boundary values */ if (iproc != 0) { /* If I'm not the first processor I want to send/receive to my previous neighbour */ MPI_Isend(prev_plate[1], SIZE, MPI_FLOAT, iproc - 1, 0, MPI_COMM_WORLD, &request); MPI_Recv(prev_plate[0], SIZE, MPI_FLOAT, iproc - 1, 0, MPI_COMM_WORLD, &status); } if (iproc != nproc - 1) { /* If I'm not the last processor I want to send/receice from my next neighbor */ MPI_Isend(prev_plate[rows_assinged], SIZE, MPI_FLOAT, iproc + 1, 0, MPI_COMM_WORLD, &request); MPI_Recv(prev_plate[rows_assinged + 1], SIZE, MPI_FLOAT, iproc + 1, 0, MPI_COMM_WORLD, &status); } /* Do the calculations */ update_plate(iproc, plate, prev_plate, locked_cells, rows_assinged, start, end); /* Check to see if we are done */ done = steady(iproc, plate, locked_cells, rows_assinged, start, end); /* Do a reduce and distribute it to all processors */ MPI_Allreduce(&done, &reallydone, 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD); /* Swap the pointers */ temp_plate = plate; plate = prev_plate; prev_plate = temp_plate; } /* print out the number of iterations to relax */ printf("%d :It took %d iterations and %lf seconds to relax the system\n", iproc, iterations, When() - starttime); /* Deallocate everything */ // cleanup(plate, rows_assinged, iproc, nproc); // cleanup(prev_plate, rows_assinged, iproc, nproc); // cleanup(locked_cells, rows_assinged, iproc, nproc); MPI_Finalize(); return EXIT_SUCCESS; }