void
EventDeliveryManager::gather_events( bool done )
{
  // IMPORTANT: Ensure that gather_events(..) is called from a single thread and
  //            NOT from a parallel OpenMP region!!!

  // Stop watch for time measurements within this function
  static Stopwatch stw_local;

  stw_local.reset();
  stw_local.start();
  collocate_buffers_( done );
  stw_local.stop();
  time_collocate_ += stw_local.elapsed();
  stw_local.reset();
  stw_local.start();
  if ( off_grid_spiking_ )
  {
    kernel().mpi_manager.communicate(
      local_offgrid_spikes_, global_offgrid_spikes_, displacements_ );
  }
  else
  {
    kernel().mpi_manager.communicate(
      local_grid_spikes_, global_grid_spikes_, displacements_ );
  }
  stw_local.stop();
  time_communicate_ += stw_local.elapsed();
}
Пример #2
0
static bool performanceTest()
{
    static const int kTableMax = 100;
    IndirectRefTable irt;
    IndirectRef manyRefs[kTableMax];
    ClassObject* clazz = dvmFindClass("Ljava/lang/Object;", NULL);
    Object* obj0 = dvmAllocObject(clazz, ALLOC_DONT_TRACK);
    const u4 cookie = IRT_FIRST_SEGMENT;
    const int kLoops = 100000;
    Stopwatch stopwatch;

    DBUG_MSG("+++ START performance\n");

    if (!irt.init(kTableMax, kTableMax, kIndirectKindGlobal)) {
        return false;
    }

    stopwatch.reset();
    for (int loop = 0; loop < kLoops; loop++) {
        for (int i = 0; i < kTableMax; i++) {
            manyRefs[i] = irt.add(cookie, obj0);
        }
        for (int i = 0; i < kTableMax; i++) {
            irt.remove(cookie, manyRefs[i]);
        }
    }
    DBUG_MSG("Add/remove %d objects FIFO order, %d iterations, %0.3fms / iteration",
            kTableMax, kLoops, stopwatch.elapsedSeconds() * 1000 / kLoops);

    stopwatch.reset();
    for (int loop = 0; loop < kLoops; loop++) {
        for (int i = 0; i < kTableMax; i++) {
            manyRefs[i] = irt.add(cookie, obj0);
        }
        for (int i = kTableMax; i-- > 0; ) {
            irt.remove(cookie, manyRefs[i]);
        }
    }
    DBUG_MSG("Add/remove %d objects LIFO order, %d iterations, %0.3fms / iteration",
            kTableMax, kLoops, stopwatch.elapsedSeconds() * 1000  / kLoops);

    for (int i = 0; i < kTableMax; i++) {
        manyRefs[i] = irt.add(cookie, obj0);
    }
    stopwatch.reset();
    for (int loop = 0; loop < kLoops; loop++) {
        for (int i = 0; i < kTableMax; i++) {
            irt.get(manyRefs[i]);
        }
    }
    DBUG_MSG("Get %d objects, %d iterations, %0.3fms / iteration",
            kTableMax, kLoops, stopwatch.elapsedSeconds() * 1000  / kLoops);
    for (int i = kTableMax; i-- > 0; ) {
        irt.remove(cookie, manyRefs[i]);
    }

    irt.destroy();
    return true;
}
Пример #3
0
		void clear()
		{
			text.clear();
			cursorPos = 0;
			leftPressStopwatch.reset();
			rightPressStopwatch.reset();
			cursorStopwatch.reset();
		}
Пример #4
0
		void update(bool currentPressed)
		{
			const bool previousPressed = pressed;

			pressed = currentPressed;

			down = !previousPressed && pressed;

			up = previousPressed && !pressed;

			if (down)
			{
				stopwatch.restart();
			}
			else if (up)
			{
				pressedDuration = stopwatch.elapsedF();

				stopwatch.reset();
			}
			else if (pressed)
			{
				pressedDuration = stopwatch.elapsedF();
			}
			else
			{
				pressedDuration = MillisecondsF(0);
			}
		}
Пример #5
0
void walk_tree()
{
    static Stopwatch timer;
    timer.start();
    
    scale_factor = sqrt(2.0*pow(((double)width/(bbmax-bbmin).max()), 2.0));
    
    vert_ls splats = sphere_tree->recurseToDepth(recursion_depth);
    
    splats.sort(testSize);
    
    maxSplatSize = scale_factor * (splats.front()->size - splats.back()-> size)/2.0;
    
    fastSplats.clear();    
    fastSplats.reserve(splats.size());
    
    for (vert_it it = splats.begin(); it != splats.end(); it++)
    {
        fastSplats.push_back(**it);
    }

    splatParts.clear();
    splatSizes.clear();
    
    partitionSizes(fastSplats.begin(), fastSplats.end(), 5);
    
    splatParts.push_back(fastSplats.end());
    
    cout << splatSizes.size() << endl;
    
    timer.stop();
    printf("Recursed to depth %u in %f seconds\n", recursion_depth, timer.time());
    printf("Displaying %lu splats, with %lu sizes\n", splats.size(), splatSizes.size() );
    timer.reset();
}
Пример #6
0
        /// <summary>
        /// EasingControllerを停止し、経過時間を0にリセットします。
        /// </summary>
         /// <returns>
        /// なし
        /// </returns>
		void reset()
		{
			if (m_swapped)
			{
				std::swap(m_start, m_end);

				m_swapped = false;
			}

			m_stopwatch.reset();
		}
Пример #7
0
        /// <summary>
        /// EasingControllerを開始、再開します。
        /// </summary>
         /// <returns>
        /// なし
        /// </returns>
		void start()
		{
			if (m_stopwatch.isActive() && m_stopwatch.ms() >= m_timeMillisec)
			{
				m_stopwatch.reset();

				std::swap(m_start, m_end);

				m_swapped = true;
			}

			m_stopwatch.start();
		}
Пример #8
0
void Main()
{
	Window::SetTitle(L"10.00");

	Stopwatch stopwatch;

	Effect effect;

	const Font font(50);

	const Vec2 pos = font(L"00.00").regionCenter(Window::Center()).pos;

	while (System::Update())
	{
		if ((!stopwatch.isActive() || stopwatch.isPaused()) && Input::MouseL.clicked)
		{
			Graphics::SetVSyncEnabled(false);
			stopwatch.start();
		}
		else if (stopwatch.isActive() && Input::MouseL.clicked)
		{
			Graphics::SetVSyncEnabled(false);
			stopwatch.pause();
		}
		else if (Input::MouseR.clicked)
		{
			stopwatch.reset();
		}
		else if (stopwatch.isPaused() && stopwatch.ms() / 10 == 10'00)
		{
			Graphics::SetVSyncEnabled(true);
			effect.add<Firework>(Circular(200, Random(TwoPi)) + Window::Center(), 30);
		}

		font(L"{:0>2}.{:0>2}"_fmt, stopwatch.s(), stopwatch.ms() % 1000 / 10).draw(pos);

		if (effect.hasEffects())
		{
			Graphics2D::SetBlendState(BlendState::Additive);

			effect.update();

			Graphics2D::SetBlendState(BlendState::Default);
		}
		else
		{
			System::Sleep(4ms);
		}
	}
}
Пример #9
0
		bool updateSingle()
		{
			double elapsed = m_stopwatch.msF();

			if (m_transitionState == TransitionState::FadeOut && elapsed >= m_transitionTimeMillisec)
			{
				m_current = nullptr;

				m_current = m_factories[m_nextState]();

				if (hasError())
				{
					return false;
				}

				m_currentState = m_nextState;

				m_transitionState = TransitionState::FadeIn;

				m_stopwatch.restart();

				elapsed = 0.0;
			}

			if (m_transitionState == TransitionState::FadeIn && elapsed >= m_transitionTimeMillisec)
			{
				m_stopwatch.reset();

				m_transitionState = TransitionState::Active;
			}

			switch (m_transitionState)
			{
			case TransitionState::FadeIn:
				assert(m_transitionTimeMillisec);
				m_current->updateFadeIn(elapsed / m_transitionTimeMillisec);
				return !hasError();
			case TransitionState::Active:
				m_current->update();
				return !hasError();
			case TransitionState::FadeOut:
				assert(m_transitionTimeMillisec);
				m_current->updateFadeOut(elapsed / m_transitionTimeMillisec);
				return !hasError();
			default:
				return false;
			}
		}
Пример #10
0
// executes functions based on choice
void doChoice(string choice, Stopwatch &stopwatch)
{

    if (choice == "toggle")
    {
        if (stopwatch.isRunning())
        {
            stopwatch.toggle();
            cout << "Stopwatch stopped at " << stopwatch.split() << " seconds." << endl;
        }
        else
        {
            cout << "Stopwatch started." << endl;
            stopwatch.toggle();
        }
    }
    else if (choice == "split")
    {
        cout << "Elapsed time is " << stopwatch.split() << " seconds." << endl;
    }
    else if (choice == "reset")
    {
        stopwatch.reset();
        cout << "Stopwatch reset." << endl;
    }
    else if (choice == "status")
    {
        if (stopwatch.isRunning())
        {
            cout << "Stopwatch is running." << endl;
            cout << "Elapsed time is " << stopwatch.split() << " seconds." << endl;
        }
        else
        {
            cout << "Stopwatch is not running." << endl;
            cout << "Elapsed time is " << stopwatch.split() << " seconds." << endl;
        }
    }
    // catch invalid input
    else
    {
        throw 1;
    }
}
Пример #11
0
		bool updateCross()
		{
			const double elapsed = m_stopwatch.msF();

			if (m_transitionState == TransitionState::FadeInOut)
			{
				if (elapsed >= m_transitionTimeMillisec)
				{
					m_current = m_next;

					m_next = nullptr;

					m_stopwatch.reset();

					m_transitionState = TransitionState::Active;
				}
			}

			if (m_transitionState == TransitionState::Active)
			{
				m_current->update();

				return !hasError();
			}
			else
			{
				assert(m_transitionTimeMillisec);

				const double t = elapsed / m_transitionTimeMillisec;

				m_current->updateFadeOut(t);

				if (hasError())
				{
					return false;
				}

				m_next->updateFadeIn(t);

				return !hasError();
			}
		}
Пример #12
0
void StopwatchTest::testStopwatch()
{
    Stopwatch sw;
    sw.start();
    Thread::sleep(200);
    sw.stop();
    Timestamp::TimeDiff d = sw.elapsed();
    assert (d >= 180000 && d <= 300000);
    sw.start();
    Thread::sleep(100);
    d = sw.elapsed();
    assert (d >= 280000 && d <= 400000);
    Thread::sleep(100);
    sw.stop();
    d = sw.elapsed();
    assert (d >= 380000 && d <= 500000);
    sw.reset();
    sw.start();
    Thread::sleep(200);
    sw.stop();
    d = sw.elapsed();
    assert (d >= 180000 && d <= 300000);
}
Пример #13
0
int main(int argc, char** argv)
{

  // char connection[50] = "localhost:5988";
  char *address_string = NULL;

    Uint32 repetitions = 1;

    // Get environment variables:

    String pegasusHome;
    pegasusHome = "/";

    // GetEnvironmentVariables(argv[0], pegasusHome);

    // Get options (from command line and from configuration file); this
    // removes corresponding options and their arguments fromt he command
    // line.

    // Get options (from command line and from configuration file); this
    // removes corresponding options and their arguments fromt he command
    // line.

    OptionManager om;

    try
    {
         GetOptions(om, argc, argv, pegasusHome);
    }
    catch (Exception& e)
    {
         cerr << argv[0] << ": " << e.getMessage() << endl;
         exit(1);
    }

    // Check to see if user asked for help (-h otpion):
    if (om.valueEquals("help", "true"))
    {
                String header = "Usage ";
                header.append(argv[0]);
                header.append(" -parameters host [host]");

                String trailer = "Assumes localhost:5988 if host not specified";
                trailer.append("\nHost may be of the form name or name:port");
                trailer.append("\nPort 5988 assumed if port number missing.");
                om.printOptionsHelpTxt(header, trailer);

         exit(0);
    }

    String localNameSpace;
    om.lookupValue("namespace", localNameSpace);
    globalNamespace = localNameSpace;
    cout << "Namespace = " << localNameSpace << endl;

    String userName;
    om.lookupValue("user", userName);
    if (userName != String::EMPTY)
    {
       cout << "Username = "******"verbose");

    String password;
    om.lookupValue("password", password);
    if (password != String::EMPTY)
    {
       cout << "password = "******"repeat", repeatTestCount))
        repeatTestCount = 1;
    /*
    if (om.lookupValue("repeat", repeats))
        {
        repeatTestCount = atol(repeats.getCString());
        }
    else
        repeatTestCount = 1;
    */
    if(verboseTest)
        cout << "Test repeat count " << repeatTestCount << endl;

    // Setup the active test flag.  Determines if we change repository.
    Boolean activeTest = false;
    if (om.valueEquals("active", "true"))
         activeTest = true;

    // here we determine the list of systems to test.
    // All arguments remaining in argv go into list.

    Boolean localConnection = (om.valueEquals("local", "true"))? true: false;
    cout << "localConnection " << (localConnection ? "true" : "false") << endl;

    Array<String> connectionList;
    if (argc > 1 && !localConnection)
         for (Sint32 i = 1; i < argc; i++)
             connectionList.append(argv[i]);

    // substitute the default if no params
    if(argc < 2)
      connectionList.append("localhost:5988");

    // Expand host to add port if not defined

    Boolean useSSL =  om.isTrue("ssl");

    // Show the connectionlist
    cout << "Connection List size " << connectionList.size() << endl;
    for (Uint32 i = 0; i < connectionList.size(); i++)
    cout << "Connection " << i << " address " << connectionList[i] << endl;

    for(Uint32 numTests = 1; numTests <= repeatTestCount; numTests++)
    {
        cout << "Test Repetition # " << numTests << endl;
        for (Uint32 i = 0; i < connectionList.size(); i++)
        {
            cout << "Start Try Block" << endl;
          try
          {
             cout << "Set Stopwatch" << endl;

             Stopwatch elapsedTime;

             cout << "Create client" << endl;
             CIMClient client;
             client.setTimeout(60 * 1000);
             cout << "Client created" << endl;

                     //
                     //  Get host and port number from connection list entry
                     //
                     Uint32 index = connectionList[i].find (':');
                     String host = connectionList[i].subString (0, index);
                     Uint32 portNumber = 0;
                     if (index != PEG_NOT_FOUND)
                     {
                         String portStr = connectionList[i].subString
                             (index + 1, connectionList[i].size ());
                         sscanf (portStr.getCString (), "%u", &portNumber);
                     }

                     if (useSSL)
             {

                        //
                        // Get environment variables:
                        //
                        const char* pegasusHome = getenv("PEGASUS_HOME");

                        String certpath = FileSystem::getAbsolutePath(
                            pegasusHome, PEGASUS_SSLCLIENT_CERTIFICATEFILE);

            String randFile;
#ifdef PEGASUS_SSL_RANDOMFILE
            randFile = FileSystem::getAbsolutePath(
                            pegasusHome, PEGASUS_SSLCLIENT_RANDOMFILE);
#endif

                        SSLContext sslcontext(certpath,verifyServerCertificate, randFile);

            if (om.isTrue("local"))
            {
                 cout << "Using local SSL connection mechanism " << endl;
                     client.connectLocal();
            }
            else
            {
                            cout << "connecting to " << connectionList[i] << " using SSL" << endl;
                            client.connect (host, portNumber, sslcontext,
                                            userName, password);
                        }
              }
                  else
              {
            if (om.isTrue("local"))
            {
                 cout << "Using local connection mechanism " << endl;
                     client.connectLocal();
            }
            else
            {
              cout << "Connecting to " << connectionList[i] << endl;
                            client.connect (host, portNumber,
                                            userName, password);
            }
              }
              cout << "Client Connected" << endl;

              testStart("Test NameSpace Operations - Relative Name");
              elapsedTime.reset();
              elapsedTime.start();
              TestNamespaceHierarchy1(client, activeTest, verboseTest);
              elapsedTime.stop();
              testEnd(elapsedTime.getElapsed());

              testStart("Test NameSpace Operations - Absolute Name");
              elapsedTime.reset();
              elapsedTime.start();
              TestNamespaceHierarchy2(client, activeTest, verboseTest);
              elapsedTime.stop();
              testEnd(elapsedTime.getElapsed());

              client.disconnect();
          }
          catch(Exception& e)
          {
               PEGASUS_STD(cerr) << "Error: " << e.getMessage() <<
                 PEGASUS_STD(endl);
               exit(1);
          }
        }
    }
    PEGASUS_STD(cout) << "+++++ "<< argv[0] << " Terminated Normally" << PEGASUS_STD(endl);
    return 0;
}
Пример #14
0
void
StreamChunker::sendFile(
				char* filename,
				IEventQueue* events,
				void* eventTarget)
{
	s_isChunkingFile = true;
	
	std::fstream file(reinterpret_cast<char*>(filename), std::ios::in | std::ios::binary);

	if (!file.is_open()) {
		throw runtime_error("failed to open file");
	}

	// check file size
	file.seekg (0, std::ios::end);
	size_t size = (size_t)file.tellg();

	// send first message (file size)
	String fileSize = synergy::string::sizeTypeToString(size);
	FileChunk* sizeMessage = FileChunk::start(fileSize);

	events->addEvent(Event(events->forFile().fileChunkSending(), eventTarget, sizeMessage));

	// send chunk messages with a fixed chunk size
	size_t sentLength = 0;
	size_t chunkSize = s_chunkSize;
	Stopwatch keepAliveStopwatch;
	Stopwatch sendStopwatch;
	keepAliveStopwatch.start();
	sendStopwatch.start();
	file.seekg (0, std::ios::beg);

	while (true) {
		if (s_interruptFile) {
			s_interruptFile = false;
			LOG((CLOG_NOTIFY "file transmission interrupted"));
			break;
		}
		
		if (keepAliveStopwatch.getTime() > KEEP_ALIVE_THRESHOLD) {
			events->addEvent(Event(events->forFile().keepAlive(), eventTarget));
			keepAliveStopwatch.reset();
		}

		if (sendStopwatch.getTime() > SEND_THRESHOLD) {
			// make sure we don't read too much from the mock data.
			if (sentLength + chunkSize > size) {
				chunkSize = size - sentLength;
			}

			char* chunkData = new char[chunkSize];
			file.read(chunkData, chunkSize);
			UInt8* data = reinterpret_cast<UInt8*>(chunkData);
			FileChunk* fileChunk = FileChunk::data(data, chunkSize);
			delete[] chunkData;

			events->addEvent(Event(events->forFile().fileChunkSending(), eventTarget, fileChunk));

			sentLength += chunkSize;
			file.seekg (sentLength, std::ios::beg);

			if (sentLength == size) {
				break;
			}

			sendStopwatch.reset();
		}
	}

	// send last message
	FileChunk* end = FileChunk::end();

	events->addEvent(Event(events->forFile().fileChunkSending(), eventTarget, end));

	file.close();
	
	s_isChunkingFile = false;
}
Пример #15
0
void
StreamChunker::sendClipboard(
				String& data,
				size_t size,
				ClipboardID id,
				UInt32 sequence,
				IEventQueue* events,
				void* eventTarget)
{
	s_isChunkingClipboard = true;
	
	// send first message (data size)
	String dataSize = synergy::string::sizeTypeToString(size);
	ClipboardChunk* sizeMessage = ClipboardChunk::start(id, sequence, dataSize);
	
	events->addEvent(Event(events->forClipboard().clipboardSending(), eventTarget, sizeMessage));

	// send clipboard chunk with a fixed size
	size_t sentLength = 0;
	size_t chunkSize = s_chunkSize;
	Stopwatch keepAliveStopwatch;
	Stopwatch sendStopwatch;
	keepAliveStopwatch.start();
	sendStopwatch.start();
	
	while (true) {
		if (s_interruptClipboard) {
			s_interruptClipboard = false;
			LOG((CLOG_NOTIFY "clipboard transmission interrupted"));
			break;
		}
		
		if (keepAliveStopwatch.getTime() > KEEP_ALIVE_THRESHOLD) {
			events->addEvent(Event(events->forFile().keepAlive(), eventTarget));
			keepAliveStopwatch.reset();
		}

		if (sendStopwatch.getTime() > SEND_THRESHOLD) {
			// make sure we don't read too much from the mock data.
			if (sentLength + chunkSize > size) {
				chunkSize = size - sentLength;
			}

			String chunk(data.substr(sentLength, chunkSize).c_str(), chunkSize);
			ClipboardChunk* dataChunk = ClipboardChunk::data(id, sequence, chunk);
			
			events->addEvent(Event(events->forClipboard().clipboardSending(), eventTarget, dataChunk));

			sentLength += chunkSize;
			if (sentLength == size) {
				break;
			}

			sendStopwatch.reset();
		}
	}

	// send last message
	ClipboardChunk* end = ClipboardChunk::end(id, sequence);

	events->addEvent(Event(events->forClipboard().clipboardSending(), eventTarget, end));
	
	s_isChunkingClipboard = false;
}
Пример #16
0
int main(int i_argc, char *i_argv[])
{
	MemBlockAlloc::setup();

	//input parameter names (specific ones for this program)
	const char *bogus_var_names[] = {
			"rexi-use-coriolis-formulation",
			"compute-error",
			nullptr
	};

	// default values for specific input (for general input see SimulationVariables.hpp)
	simVars.bogus.var[0] = 0;
	simVars.bogus.var[1] = 0;

	// Help menu
	if (!simVars.setupFromMainParameters(i_argc, i_argv, bogus_var_names))
	{
#if SWEET_PARAREAL
		simVars.parareal.setup_printOptions();
#endif
		return -1;
	}

	param_rexi_use_coriolis_formulation = simVars.bogus.var[0];
	assert (param_rexi_use_coriolis_formulation == 0 || param_rexi_use_coriolis_formulation == 1);

	param_compute_error = simVars.bogus.var[1];

	sphereDataConfigInstance.setupAutoPhysicalSpace(
					simVars.disc.res_spectral[0],
					simVars.disc.res_spectral[1],
					&simVars.disc.res_physical[0],
					&simVars.disc.res_physical[1]
			);


#if SWEET_GUI
	planeDataConfigInstance.setupAutoSpectralSpace(simVars.disc.res_physical);
#endif


	std::ostringstream buf;
	buf << std::setprecision(14);

#if 0
	SimulationInstance test_swe(sphereDataConfig);
	test_swe.run();
#else

#if SWEET_MPI
	int rank;
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);

	// only start simulation and time stepping for first rank
	if (rank == 0)
#endif
	{
#if SWEET_PARAREAL
		if (simVars.parareal.enabled)
		{
			/*
			 * Allocate parareal controller and provide class
			 * which implement the parareal features
			 */
			Parareal_Controller_Serial<SimulationInstance> parareal_Controller_Serial;

			// setup controller. This initializes several simulation instances
			parareal_Controller_Serial.setup(&simVars.parareal);

			// execute the simulation
			parareal_Controller_Serial.run();
		}
		else
#endif

#if SWEET_GUI // The VisSweet directly calls simulationSWE->reset() and output stuff
		if (simVars.misc.gui_enabled)
		{
			SimulationInstance *simulationSWE = new SimulationInstance;
			VisSweet<SimulationInstance> visSweet(simulationSWE);
			delete simulationSWE;
		}
		else
#endif
		{
			SimulationInstance *simulationSWE = new SimulationInstance;
			//Setting initial conditions and workspace - in case there is no GUI

			simulationSWE->reset();

			//Time counter
			Stopwatch time;

			//Diagnostic measures at initial stage
			//double diagnostics_energy_start, diagnostics_mass_start, diagnostics_potential_entrophy_start;

			// Initialize diagnostics
			if (simVars.misc.verbosity > 0)
			{
				simulationSWE->update_diagnostics();
#if 0
				diagnostics_energy_start = simVars.diag.total_energy;
				diagnostics_mass_start = simVars.diag.total_mass;
				diagnostics_potential_entrophy_start = simVars.diag.total_potential_enstrophy;
#endif
			}

#if SWEET_MPI
			MPI_Barrier(MPI_COMM_WORLD);
#endif
			//Start counting time
			time.reset();


			// Main time loop
			while(true)
			{
				if (simulationSWE->timestep_output(buf))
				{
					// string output data

					std::string output = buf.str();
					buf.str("");

					// This is an output printed on screen or buffered to files if > used
					std::cout << output;
				}

				// Stop simulation if requested
				if (simulationSWE->should_quit())
					break;

				// Main call for timestep run
				simulationSWE->run_timestep();

				// Instability
				if (simulationSWE->instability_detected())
				{
					std::cout << "INSTABILITY DETECTED" << std::endl;
					break;
				}
			}

			// Always write or overwrite final time step output!
			simulationSWE->write_file_output();

			// Stop counting time
			time.stop();

			double seconds = time();

			// End of run output results
			std::cout << "Simulation time (seconds): " << seconds << std::endl;
			std::cout << "Number of time steps: " << simVars.timecontrol.current_timestep_nr << std::endl;
			std::cout << "Time per time step: " << seconds/(double)simVars.timecontrol.current_timestep_nr << " sec/ts" << std::endl;
			std::cout << "Last time step size: " << simVars.timecontrol.current_timestep_size << std::endl;

			if (param_compute_error && simVars.misc.use_nonlinear_equations == 0)
			{
				SphereData backup_h = simulationSWE->prog_h;
				SphereData backup_u = simulationSWE->prog_u;
				SphereData backup_v = simulationSWE->prog_v;

				simulationSWE->reset();

				std::cout << "DIAGNOSTICS ANALYTICAL RMS H:\t" << (backup_h-simulationSWE->prog_h).physical_reduce_rms() << std::endl;
				std::cout << "DIAGNOSTICS ANALYTICAL RMS U:\t" << (backup_u-simulationSWE->prog_u).physical_reduce_rms() << std::endl;
				std::cout << "DIAGNOSTICS ANALYTICAL RMS V:\t" << (backup_v-simulationSWE->prog_v).physical_reduce_rms() << std::endl;

				std::cout << "DIAGNOSTICS ANALYTICAL MAXABS H:\t" << (backup_h-simulationSWE->prog_h).physical_reduce_max_abs() << std::endl;
				std::cout << "DIAGNOSTICS ANALYTICAL MAXABS U:\t" << (backup_u-simulationSWE->prog_u).physical_reduce_max_abs() << std::endl;
				std::cout << "DIAGNOSTICS ANALYTICAL MAXABS V:\t" << (backup_v-simulationSWE->prog_v).physical_reduce_max_abs() << std::endl;
			}

			delete simulationSWE;
		}
	}
#if SWEET_MPI
	else
	{
		if (param_timestepping_mode == 1)
		{
			SWE_Plane_REXI rexiSWE;

			/*
			 * Setup our little dog REXI
			 */
			rexiSWE.setup(
					simVars.rexi.rexi_h,
					simVars.rexi.rexi_m,
					simVars.rexi.rexi_l,
					simVars.disc.res_physical,
					simVars.sim.domain_size,
					simVars.rexi.rexi_half,
					simVars.rexi.rexi_use_spectral_differences_for_complex_array,
					simVars.rexi.rexi_helmholtz_solver_id,
					simVars.rexi.rexi_helmholtz_solver_eps
				);

			bool run = true;

			PlaneData prog_h(planeDataConfig);
			PlaneData prog_u(planeDataConfig);
			PlaneData prog_v(planeDataConfig);

			PlaneOperators op(simVars.disc.res_physical, simVars.sim.domain_size, simVars.disc.use_spectral_basis_diffs);

			MPI_Barrier(MPI_COMM_WORLD);

			while (run)
			{
				// REXI time stepping
				run = rexiSWE.run_timestep_rexi(
						prog_h, prog_u, prog_v,
						-simVars.sim.CFL,
						op,
						simVars
				);
			}
		}
	}
#endif


#if SWEET_MPI
	if (param_timestepping_mode > 0)
	{
		// synchronize REXI
		if (rank == 0)
			SWE_Plane_REXI::MPI_quitWorkers(planeDataConfig);
	}

	MPI_Finalize();
#endif

#endif
	return 0;
}
Пример #17
0
int
FileChunk::assemble(synergy::IStream* stream, String& dataReceived, size_t& expectedSize)
{
	// parse
	UInt8 mark = 0;
	String content;
	static size_t receivedDataSize;
	static double elapsedTime;
	static Stopwatch stopwatch;

	if (!ProtocolUtil::readf(stream, kMsgDFileTransfer + 4, &mark, &content)) {
		return kError;
	}

	switch (mark) {
	case kDataStart:
		dataReceived.clear();
		expectedSize = synergy::string::stringToSizeType(content);
		receivedDataSize = 0;
		elapsedTime = 0;
		stopwatch.reset();

		if (CLOG->getFilter() >= kDEBUG2) {
			LOG((CLOG_DEBUG2 "recv file data from client: file size=%s", content.c_str()));
			stopwatch.start();
		}
		return kStart;

	case kDataChunk:
		dataReceived.append(content);
		if (CLOG->getFilter() >= kDEBUG2) {
				LOG((CLOG_DEBUG2 "recv file data from client: chunck size=%i", content.size()));
				double interval = stopwatch.getTime();
				receivedDataSize += content.size();
				LOG((CLOG_DEBUG2 "recv file data from client: interval=%f s", interval));
				if (interval >= kIntervalThreshold) {
					double averageSpeed = receivedDataSize / interval / 1000;
					LOG((CLOG_DEBUG2 "recv file data from client: average speed=%f kb/s", averageSpeed));

					receivedDataSize = 0;
					elapsedTime += interval;
					stopwatch.reset();
				}
			}
		return kNotFinish;

	case kDataEnd:
		if (expectedSize != dataReceived.size()) {
			LOG((CLOG_ERR "corrupted clipboard data, expected size=%d actual size=%d", expectedSize, dataReceived.size()));
			LOG((CLOG_NOTIFY "File Transmission Failed: Corrupted file data."));
			return kError;
		}

		if (CLOG->getFilter() >= kDEBUG2) {
			LOG((CLOG_DEBUG2 "file data transfer finished"));
			elapsedTime += stopwatch.getTime();
			double averageSpeed = expectedSize / elapsedTime / 1000;
			LOG((CLOG_DEBUG2 "file data transfer finished: total time consumed=%f s", elapsedTime));
			LOG((CLOG_DEBUG2 "file data transfer finished: total data received=%i kb", expectedSize / 1000));
			LOG((CLOG_DEBUG2 "file data transfer finished: total average speed=%f kb/s", averageSpeed));
		}
		return kFinish;
	}

	return kError;
}
Пример #18
0
int main(int argc, char *argv[])
{
    int test = argc > 1 ? atoi(argv[1]) : 0;
    int verbose = argc > 2;
    int veryVerbose = argc > 3;
    int veryVeryVerbose = argc > 4;

    (void) veryVeryVerbose;

    printf("TEST " __FILE__ " CASE %d\n", test);

    switch (test) { case 0:  // Zero is always the leading case.


      case 5: {
        // --------------------------------------------------------------------
        // TESTING USAGE EXAMPLE 3
        //   This will test the usage example 3 provided in the component
        //   header file for 'prefetchForReading' and 'prefetchForWriting'.
        //
        // Concerns:
        //   The usage example provided in the component header file must
        //   compile, link, and run on all platforms as shown.
        //
        // Plan:
        //   Run the usage example using 'prefetchForReading' and
        //   'prefetchForWriting'.
        //
        // Testing:
        //   prefetchForReading
        //   prefetchForWriting
        // --------------------------------------------------------------------

        if (verbose) printf("\nTESTING USAGE EXAMPLE 3"
                            "\n=======================\n");

        UsageExample3Case::testUsageExample3(argc, false);

      } break;
      case 4: {
        // --------------------------------------------------------------------
        // TESTING USAGE EXAMPLE 2
        //   This will test the usage example 2 provided in the component
        //   header file for 'BSLS_PERFORMANCEHINT_PREDICT_EXPECT'.
        //
        // Concerns:
        //   The usage example provided in the component header file must
        //   compile, link, and run on all platforms as shown.
        //
        // Plan:
        //   Ensure the usage example compiles.
        //
        // Testing:
        //   BSLS_PERFORMANCEHINT_PREDICT_EXPECT
        // --------------------------------------------------------------------

        if (verbose) printf("\nTESTING USAGE EXAMPLE 2"
                            "\n=======================\n");

        int x = rand() % 4;

        // Incorrect usage of 'BSLS_PERFORMANCEHINT_PREDICT_EXPECT', since the
        // probability of getting a 3 is equivalent to other numbers (0, 1, 2).
        // However, this is sufficient to illustrate the intent of this macro.

        switch(BSLS_PERFORMANCEHINT_PREDICT_EXPECT(x, 3)) {
          case 1: //..
                  break;
          case 2: //..
                  break;
          case 3: //..
                  break;
          default: break;
        }

      } break;
      case 3: {
        // --------------------------------------------------------------------
        // TESTING USAGE EXAMPLE 1
        //   This will test the usage example 1 provided in the component
        //   header file for 'BSLS_PERFORMANCEHINT_PREDICT_LIKELY' and
        //   'BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY'.
        //
        // Concerns:
        //   The usage example provided in the component header file must
        //   compile, link, and run on all platforms as shown.
        //
        // Plan:
        //   Run the usage example using 'BSLS_PERFORMANCEHINT_PREDICT_LIKELY'
        //   and 'BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY'.
        //
        // Testing:
        //   BSLS_PERFORMANCEHINT_PREDICT_LIKELY,
        //   BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY
        // --------------------------------------------------------------------

        if (verbose) printf("\nTESTING USAGE EXAMPLE 1"
                            "\n=======================\n");


        ASSERT(true);
        UsageExample1Case::testUsageExample1(argc, true);

      } break;

      case 2: {
        // --------------------------------------------------------------------
        // TESTING: BSLS_PERFORMANCEHINT_OPTIMIZATION_FENCE
        //
        // Concerns:
        //: 1 'OPTIMIZATION_FENCE' compiles on all platforms.
        //:
        //: 2 On platforms on which it is reasonably implemented,
        //:   'OPTIMIZATION_FENCE' impedes compiler optimizations on optimized
        //:   builds.
        //
        // Plan:
        //: 1 Perform a simple loop incrementing a counter for a set period of
        //:   time, both with and without the use of the 'OPTMIZATION_FENCE'.
        //:   Use a timer to verify the rate of increments using the
        //:   'OPTIMIZATION_FENCE' is slower.  Note that in practice, on
        //:   platforms on which the fence is reasonably implemented (*not*
        //:   older versions of Sun CC), the iteration with the
        //:   'OPTIMIZATION_FENCE" is very noticeably slower (several times
        //:   slower).
        //
        // Testing:
        //   BSLS_PERFORMANCEHINT_OPTIMIZATION_FENCE
        // --------------------------------------------------------------------

        if (verbose) printf(
            "\nTESTING: BSLS_PERFORMANCEHINT_OPTIMIZATION_FENCE"
            "\n================================================\n");

        ReorderingFenceTestCase::testReorderingFence(argc);

      } break;
      case 1: {
        // --------------------------------------------------------------------
        // TESTING TEST-MACHINERY: 'Stopwatch'
        //
        // Concerns:
        //: 1 That 'Stopwatch' is created in a STOPPED state with an elapsed
        //:   time of 0.
        //:
        //: 2 That 'start' puts the stopwatch in a RUNNING state
        //:
        //: 3 That 'stop' puts the soptwatch in a STOPPED state and recurds
        //:   the accumuted time.
        //:
        //: 4 That 'elaspsedTime' returns the correct elapsed time in
        //:   nanoseconds.
        //:
        //: 5 That 'reset' resets the 'Stopwatch' to its defualt constructed
        //:   state.
        //
        // Plan:
        //: 1 Construct a 'Stopwatch' and verify 'isRunning' is 'false' and
        //:   'elapsedTime' is 0. (C-1)
        //:
        //: 2 Construct a 'Stopwatch', call 'start', sleep for ~1 second and
        //:   verify 'isRunning' it 'true' and 'elapsedTime' is ~1 second.
        //:
        //: 2 Construct a 'Stopwatch', call 'start', sleep for ~1 second and
        //:   then stop the 'Stopwatch'.  Sleep another second. Verify
        //:   'isRunning' it 'false', 'elapsedTime' is ~1, and that the elapsed
        //:   time has not changed since the stopwatch was stopped.
        //
        // Testing:
        //   TESTING TEST-MACHINERY: 'Stopwatch'
        // --------------------------------------------------------------------

        if (verbose) printf("\nTESTING TEST-MACHINERY: 'Stopwatch'"
                            "\n===================================\n");

        const double TOLERANCE = .5;

        if (veryVerbose) printf("\tCompare constructed 'Stopwatch'\n");
        {
            Stopwatch mX; const Stopwatch& X = mX;

            ASSERT(false == X.isRunning());
            ASSERT(0     == X.elapsedTime());
        }

        if (veryVerbose) printf("Test starting a stopwatch\n");
        {
            Stopwatch mX; const Stopwatch& X = mX;

            ASSERT(false == X.isRunning());
            ASSERT(0     == X.elapsedTime());

            mX.start();
            sleep(1);

            ASSERT(true  == X.isRunning());
            ASSERT(1 - TOLERANCE <  X.elapsedTime());
            ASSERT(1 + TOLERANCE >  X.elapsedTime());
        }

        if (veryVerbose) printf("Test stop and elapsedTime\n");
        {
            Stopwatch mX; const Stopwatch& X = mX;

            ASSERT(false == X.isRunning());
            ASSERT(0     == X.elapsedTime());

            mX.start();
            sleep(1);

            ASSERT(true  == X.isRunning());
            ASSERT(0     <  X.elapsedTime());

            mX.stop();

            double EXPECTED = X.elapsedTime();

            sleep(1);

            double ACTUAL   = X.elapsedTime();
            ASSERTV(EXPECTED, ACTUAL,
                    EXPECTED - EXPECTED * .00001 < ACTUAL &&
                    EXPECTED + EXPECTED * .00001 > ACTUAL);
            ASSERTV(X.elapsedTime(), 1 - TOLERANCE <  X.elapsedTime());
            ASSERTV(X.elapsedTime(), 1 + TOLERANCE >  X.elapsedTime());

            mX.reset();

            ASSERT(false == X.isRunning());
            ASSERT(0     == X.elapsedTime());
        }
      } break;
      case -1: {
        // --------------------------------------------------------------------
        // PERFORMANCE TEST
        //   Test the improvement of performance in using various performance
        //   hints.
        //
        // Concerns:
        //   The performance of using the performance hints in the various
        //   usage examples must be faster than not using them.
        //
        // Plan:
        //   Using 'Stopwatch', compare the time it takes to run the test
        //   using the performance hints and not using the hints.  Then compare
        //   and assert the time difference.  The test driver must observe an
        //   improvement in performance.  To minimize the effect of caching
        //   biasing the result, run the version that uses the proper hint
        //   first.
        //
        // Testing:
        //   PERFORMANCE TEST
        // --------------------------------------------------------------------

        if (verbose) printf("\nPERFORMANCE TEST"
                            "\n================\n");

        if (veryVerbose) {
            printf("Usage Example 1:\n");
        }

        UsageExample1Case::testUsageExample1(argc, true);

        if (veryVerbose) {
            printf("Usage Example 3:\n");
        }

        UsageExample3Case::testUsageExample3(argc, true);

      } break;
      case -2: {
        // --------------------------------------------------------------------
        // CONCERN: STOPWATCH ACCURACY
        //   This test is concerned with the accuracy of 'Stopwatch'. It is a
        //   negative test case because it takes ~1 minute to run.

        // Concerns:
        //: 1 That the 'elapsedTime' reported by 'Stopwatch' is accurate.
        //
        // Plan:
        //: 1 Perform a loop-based tested, sleeping over a series of different
        //:   delay periods and comparing the results of
        //:   'Stopwatch::elapsedTime' to 'time'
        //
        // Testing:
        //   CONCERN: STOPWATCH ACCURACY
        // --------------------------------------------------------------------

        if (verbose) printf("\nCONCERN: STOPWATCH ACCURACY"
                            "\n===========================\n");

        if (veryVerbose) printf("\tCompare results w/ 'time'\n");

        for (int i = 1; i < 7; ++i){
            const int DELAY = i;

            time_t    startTime = time(0);
            Stopwatch mX;
            mX.start();

            sleep(DELAY);

            mX.stop();
            time_t expectedElaspedTime = time(0) - startTime;

            if (veryVerbose) {
                P_(DELAY); P_(mX.elapsedTime()); P(expectedElaspedTime);
            }
            ASSERT(mX.elapsedTime() < expectedElaspedTime + 1 &&
                   mX.elapsedTime() > expectedElaspedTime - 1);
        }
      } break;
       default: {
        fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test);
        testStatus = -1;
      }
    }

    if (testStatus > 0) {
        fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus);
    }
    return testStatus;
}
Пример #19
0
void testUsageExample3(int argc, bool assert)
{
    int verbose = argc > 2;
    int veryVerbose = argc > 3;
    int veryVeryVerbose = argc > 4;

    // suppress 'unused parameter' compiler warnings:
    (void) assert;
    (void) verbose;
    (void) veryVeryVerbose;

    if (veryVerbose) {
        printf("Adding without prefetch\n");
    }

    UsageExample3Case::init(UsageExample3Case::array1,
                            UsageExample3Case::array2);

    Stopwatch timer;
    timer.start();

    for(int i = 0; i < TESTSIZE; ++i) {
        UsageExample3Case::addWithoutPrefetch(UsageExample3Case::array1,
                                              UsageExample3Case::array2);
    }

    timer.stop();
    double withoutPrefetch = timer.elapsedTime();

    if (veryVerbose) {
        P(withoutPrefetch);
    }

    if (veryVerbose) {
        printf("Adding with prefetch\n");
    }

    UsageExample3Case::init(UsageExample3Case::array3,
                            UsageExample3Case::array4);

    timer.reset();
    timer.start();

    for(int i = 0; i < UsageExample3Case::TESTSIZE; ++i) {
        addWithPrefetch(array3, array4);
    }

    timer.stop();
    double withPrefetch = timer.elapsedTime();

    if (veryVerbose) {
        P(withPrefetch);
    }

#if defined(BDE_BUILD_TARGET_OPT)
    // Only check under optimized build.

#if defined(BSLS_PLATFORM_CMP_CLANG)                                          \
 || defined(BSLS_PLATFORM_CMP_GNU)                                            \
 || defined(BSLS_PLATFORM_CMP_SUN)                                            \
 || defined(BSLS_PLATFORM_CMP_IBM)                                            \
 || defined(BSLS_PLATFORM_OS_WINDOWS)
    // Only check when 'prefetchForReading' or 'prefetchForWriting' expands
    // expands into something meaningful.

    double tolerance = 0.02;

    // Note that when compiling using 'bde_build.pl -t opt_exc_mt', the
    // optimization flag is set to '-O'.  Whereas, the optimization flag used
    // by 'IS_OPTIMIZED=1 pcomp' is set to '-xO2'.  Therefore, the improvement
    // in efficiency is much less than what's described in the usage example
    // when compiled using bde_build.

    if (assert) {
        // Only assert in performance test case.
        LOOP2_ASSERT(withoutPrefetch, withPrefetch,
                     withoutPrefetch + tolerance > withPrefetch);
    }

#endif

#endif

}
Пример #20
0
void testUsageExample1(int argc, bool assert)
{
    int verbose = argc > 2;
    int veryVerbose = argc > 3;
    int veryVeryVerbose = argc > 4;

    double tolerance = 0.05;

    (void) assert;
    (void) verbose;
    (void) veryVerbose;
    (void) veryVeryVerbose;
    (void) tolerance;

    Stopwatch timer;

    timer.reset();

    if (veryVerbose) {
        printf("BSLS_PERFORMANCEHINT_PREDICT_LIKELY\n");
    }

    timer.start();

    for (int x = 0; x < TESTSIZE; ++x) {
        int y = rand() % 100;

        // Incorrect usage of 'BSLS_PERFORMANCEHINT_PREDICT_LIKELY' since there
        // is only a one in 100 chance that this branch is taken.

        if (BSLS_PERFORMANCEHINT_PREDICT_LIKELY(y == 8)) {
            foo();
        }
        else {
            BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
            bar();
        }
    }

    timer.stop();
    double likelyTime = timer.elapsedTime();

    if (veryVerbose) {
        P(likelyTime);
    }


    if (veryVerbose) {
        printf("BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY\n");
    }

    timer.reset();
    timer.start();

    for (int x = 0; x < TESTSIZE; ++x) {
        int y = rand() % 100;

        // Correct usage of 'BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY' since there
        // is only a one in 100 chance that this branch is taken.

        if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(y == 8)) {
            BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
            foo();
        }
        else {
            bar();
        }
    }
    timer.stop();
    double unlikelyTime = timer.elapsedTime();

    if (veryVerbose) {
        P(unlikelyTime);
    }

#if defined(BDE_BUILD_TARGET_OPT)
    // Only check under optimized build.

#if defined(BSLS_PLATFORM_CMP_CLANG)                                          \
 || defined(BSLS_PLATFORM_CMP_GNU)                                            \
 || defined(BSLS_PLATFORM_CMP_SUN)                                            \
 || (defined(BSLS_PLATFORM_CMP_IBM) && BSLS_PLATFORM_CMP_VERSION >= 0x0900)
    // Only check when 'BSLS_PERFORMANCEHINT_PREDICT_LIKELY' and
    // 'BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY' expands into something
    // meaningful.

    if (assert) {
        LOOP2_ASSERT(likelyTime, unlikelyTime,
                     likelyTime + tolerance > unlikelyTime);
    }

#endif

#endif

}
int main(int i_argc, char *i_argv[])
{
	if (!simVars.setupFromMainParameters(i_argc, i_argv))
	{
		return -1;
	}

	planeDataConfigInstance.setupAuto(simVars.disc.res_physical, simVars.disc.res_spectral);

	SimulationSWE *simulationSWE = new SimulationSWE;

	std::ostringstream buf;

#if SWEET_GUI
	if (simVars.misc.gui_enabled)
	{
		VisSweet<SimulationSWE> visSweet(simulationSWE);
	}
	else
#endif
	{
		simulationSWE->reset();

		Stopwatch time;
		time.reset();

		double diagnostics_energy_start, diagnostics_mass_start, diagnostics_potential_entrophy_start;

		if (simVars.misc.verbosity > 1)
		{
			simulationSWE->update_diagnostics();
			diagnostics_energy_start = simVars.diag.total_energy;
			diagnostics_mass_start = simVars.diag.total_mass;
			diagnostics_potential_entrophy_start = simVars.diag.total_potential_enstrophy;
		}

		while (true)
		{
			if (simVars.misc.verbosity > 1)
			{
				simulationSWE->timestep_output(buf);

				std::string output = buf.str();
				buf.str("");

				std::cout << output << std::flush;
			}

			if (simulationSWE->should_quit())
				break;

			simulationSWE->run_timestep();

			if (simulationSWE->instability_detected())
			{
				std::cout << "INSTABILITY DETECTED" << std::endl;
				break;
			}
		}

		time.stop();

		double seconds = time();

		std::cout << "Simulation time: " << seconds << " seconds" << std::endl;
		std::cout << "Time per time step: " << seconds/(double)simVars.timecontrol.current_timestep_nr << " sec/ts" << std::endl;
		std::cout << "Timesteps: " << simVars.timecontrol.current_timestep_nr << std::endl;

		if (simVars.misc.verbosity > 1)
		{
			std::cout << "DIAGNOSTICS ENERGY DIFF:\t" << std::abs((simVars.diag.total_energy-diagnostics_energy_start)/diagnostics_energy_start) << std::endl;
			std::cout << "DIAGNOSTICS MASS DIFF:\t" << std::abs((simVars.diag.total_mass-diagnostics_mass_start)/diagnostics_mass_start) << std::endl;
			std::cout << "DIAGNOSTICS POTENTIAL ENSTROPHY DIFF:\t" << std::abs((simVars.diag.total_potential_enstrophy-diagnostics_potential_entrophy_start)/diagnostics_potential_entrophy_start) << std::endl;

			if (simVars.setup.benchmark_scenario_id == 2 || simVars.setup.benchmark_scenario_id == 3 || simVars.setup.benchmark_scenario_id == 4)
			{
				std::cout << "DIAGNOSTICS BENCHMARK DIFF H:\t" << simulationSWE->benchmark_diff_h << std::endl;
				std::cout << "DIAGNOSTICS BENCHMARK DIFF U:\t" << simulationSWE->benchmark_diff_u << std::endl;
				std::cout << "DIAGNOSTICS BENCHMARK DIFF V:\t" << simulationSWE->benchmark_diff_v << std::endl;
			}
		}
	}

	delete simulationSWE;

	return 0;
}
Пример #22
0
void LinearHashTableTest::testPerformanceStr()
{
    const int N = 5000000;
    Stopwatch sw;

    std::vector<std::string> values;
    for (int i = 0; i < N; ++i)
    {
        values.push_back(NumberFormatter::format0(i, 8));
    }

    {
        LinearHashTable<std::string, Hash<std::string> > lht(N);
        sw.start();
        for (int i = 0; i < N; ++i)
        {
            lht.insert(values[i]);
        }
        sw.stop();
        std::cout << "Insert LHT: " << sw.elapsedSeconds() << std::endl;
        sw.reset();

        sw.start();
        for (int i = 0; i < N; ++i)
        {
            lht.find(values[i]);
        }
        sw.stop();
        std::cout << "Find LHT: " << sw.elapsedSeconds() << std::endl;
        sw.reset();
    }

    {
        HashTable<std::string, int> ht;

        sw.start();
        for (int i = 0; i < N; ++i)
        {
            ht.insert(values[i], i);
        }
        sw.stop();
        std::cout << "Insert HT: " << sw.elapsedSeconds() << std::endl;
        sw.reset();

        sw.start();
        for (int i = 0; i < N; ++i)
        {
            ht.exists(values[i]);
        }
        sw.stop();
        std::cout << "Find HT: " << sw.elapsedSeconds() << std::endl;
    }

    {
        std::set<std::string> s;
        sw.start();
        for (int i = 0; i < N; ++i)
        {
            s.insert(values[i]);
        }
        sw.stop();
        std::cout << "Insert set: " << sw.elapsedSeconds() << std::endl;
        sw.reset();

        sw.start();
        for (int i = 0; i < N; ++i)
        {
            s.find(values[i]);
        }
        sw.stop();
        std::cout << "Find set: " << sw.elapsedSeconds() << std::endl;
        sw.reset();
    }
}
Пример #23
0
void LinearHashTableTest::testPerformanceInt()
{
    const int N = 5000000;
    Stopwatch sw;

    {
        LinearHashTable<int, Hash<int> > lht(N);
        sw.start();
        for (int i = 0; i < N; ++i)
        {
            lht.insert(i);
        }
        sw.stop();
        std::cout << "Insert LHT: " << sw.elapsedSeconds() << std::endl;
        sw.reset();

        sw.start();
        for (int i = 0; i < N; ++i)
        {
            lht.find(i);
        }
        sw.stop();
        std::cout << "Find LHT: " << sw.elapsedSeconds() << std::endl;
        sw.reset();
    }

    {
        HashTable<int, int> ht;

        sw.start();
        for (int i = 0; i < N; ++i)
        {
            ht.insert(i, i);
        }
        sw.stop();
        std::cout << "Insert HT: " << sw.elapsedSeconds() << std::endl;
        sw.reset();

        sw.start();
        for (int i = 0; i < N; ++i)
        {
            ht.exists(i);
        }
        sw.stop();
        std::cout << "Find HT: " << sw.elapsedSeconds() << std::endl;
    }

    {
        std::set<int> s;
        sw.start();
        for (int i = 0; i < N; ++i)
        {
            s.insert(i);
        }
        sw.stop();
        std::cout << "Insert set: " << sw.elapsedSeconds() << std::endl;
        sw.reset();

        sw.start();
        for (int i = 0; i < N; ++i)
        {
            s.find(i);
        }
        sw.stop();
        std::cout << "Find set: " << sw.elapsedSeconds() << std::endl;
        sw.reset();
    }

}