示例#1
0
void QVirtualClock::timerCallBack( std::chrono::duration<double>& elapsed_sleep_seconds )
{
    UInt32 elapsed_sec = static_cast<UInt32>(elapsed_sleep_seconds.count( ));
    
    if (elapsed_sec < 1)
    {
        return; //this should never happen because boost::sleep guarantees it.
    }
    
    if (!m_update_time_invoked)
    {
        //This can happen if pdu reception is not yet started, or if for some reason pdus have not
        // been received from one timerCallBack invocation to another, or if pdus have stopped completely.
        //The solution is to keep virtual time alive
        UInt32 elapsed_msec_fraction   = (static_cast<UInt32>(elapsed_sleep_seconds.count( ) *1000000)) % 1000000;
        UInt64 virtual_time_correction = (static_cast<UInt64>(elapsed_sec) << 32 | elapsed_msec_fraction);
        
        m_virtual_time+=virtual_time_correction;
    }

    for (UInt32 i = 0; i < elapsed_sec; i++)
    {
        ++m_total_elapsed_seconds;

        propagateTimePulseEventToRegistered();
    }

    m_update_time_invoked = false;
}
示例#2
0
文件: stats.hpp 项目: Zereges/2048RP
 //! Increments statistics for lose event.
 //! \param duration Duration of that game play.
 void game_over(const std::chrono::duration<long long>& duration)
 {
     ++m_stats[StatTypes::GAME_LOSES];
     m_stats[StatTypes::FASTEST_LOSE] = m_stats[StatTypes::FASTEST_LOSE] != 0 ? std::min(duration.count(), m_stats[StatTypes::FASTEST_LOSE]) : duration.count();
     m_stats[StatTypes::SLOWEST_LOSE] = std::max(duration.count(), m_stats[StatTypes::SLOWEST_LOSE]);
     m_stats[StatTypes::TOTAL_TIME_PLAYED] += duration.count();
 }
示例#3
0
文件: stats.hpp 项目: Zereges/2048RP
 //! Increments statistics for win event.
 //! \param duration Duration of that game play.
 void won(const std::chrono::duration<long long>& duration)
 {
     ++m_stats[StatTypes::GAME_WINS];
     m_stats[StatTypes::FASTEST_WIN] = m_stats[StatTypes::FASTEST_WIN] != 0 ? std::min(duration.count(), m_stats[StatTypes::FASTEST_WIN]) : duration.count();
     m_stats[StatTypes::SLOWEST_WIN] = std::max(duration.count(), m_stats[StatTypes::SLOWEST_WIN]);
     m_stats[StatTypes::TOTAL_TIME_PLAYED] += duration.count();
 }
示例#4
0
文件: driver.cpp 项目: kexianda/misc
void bench() {
    
    warmup();
    const int itrNum = 50;
    int size = 1024 * 1024 * 1024;
    char* s1 = (char*) malloc(sizeof (char) * size);
    char* s2 = (char*) malloc(sizeof (char) * size);
    for (int i = 0; i < size; i++)
        s1[i] = ('a' + i % 26);
    
    int blocksizes[] = {8, 16, 128, 512, 1024, 
                        4096, 1024 * 1024, 1024 * 1024 * 4, 1024 * 1024 * 8, 
                        73, 113, 1024 * 1024 + 97};
   
    {
        
        for (int i = 0; i < sizeof(blocksizes)/sizeof(int); i++) {
            
            const auto t1 = std::chrono::high_resolution_clock::now();
            int num = size / blocksizes[i];
            
            for (int itr = 0; itr < itrNum; itr++) {
                for (int j = 0; j < num; j++) {
                    memcpy((s2 + blocksizes[i] * j), (s1 + blocksizes[i] * j), blocksizes[i]);
                }
            }

            const auto t2 = std::chrono::high_resolution_clock::now();
            const std::chrono::duration<double> td = t2 - t1;
            double result = ((double)itrNum*(size/(1024*1024))) / td.count();
            printf("glibc,memcpy:\tblockSize=%d, \t\tresult = %10.6f MB/s,\ttime = %10.6f s\n", blocksizes[i], result, td.count()); 
        }
    }

    {
        
        for (int i = 0; i < sizeof (blocksizes) / sizeof (int); i++) {

            const auto t1 = std::chrono::high_resolution_clock::now();
            int num = size / blocksizes[i];

            for (int itr = 0; itr < itrNum; itr++) {
                for (int j = 0; j < num; j++) {
                    _i_memcpy_256_unaligned((s2 + blocksizes[i] * j), (s1 + blocksizes[i] * j), blocksizes[i]);
                }
            }

            const auto t2 = std::chrono::high_resolution_clock::now();
            const std::chrono::duration<double> td = t2 - t1;
            double result = ((double) itrNum * (size / (1024 * 1024))) / td.count();
            printf("our poc memcpy:\tblockSize=%d,  \t\tresult = %10.6f MB/s,\ttime = %10.6f s\n", blocksizes[i], result, td.count());
        }         
    }
}
示例#5
0
void
SinkClient::update(Observable<std::shared_ptr<VideoFrame>>* /*obs*/,
                   const std::shared_ptr<VideoFrame>& frame_p)
{
    auto& f = *frame_p;

#ifdef DEBUG_FPS
    auto currentTime = std::chrono::system_clock::now();
    const std::chrono::duration<double> seconds = currentTime - lastFrameDebug_;
    ++frameCount_;
    if (seconds.count() > 1) {
        std::ostringstream fps;
        fps << frameCount_ / seconds.count();
        // Send the framerate in smartInfo
        Smartools::getInstance().setFrameRate(id_, fps.str());
        frameCount_ = 0;
        lastFrameDebug_ = currentTime;
    }
#endif

#if HAVE_SHM
    // Send the resolution in smartInfo
    Smartools::getInstance().setResolution(id_, f.width(), f.height());
    shm_->renderFrame(f);
#endif

    if (target_.pull) {
        VideoFrame dst;
        VideoScaler scaler;
        const int width = f.width();
        const int height = f.height();
#if (defined(__ANDROID__) || defined(__APPLE__))
        const int format = VIDEO_PIXFMT_RGBA;
#else
        const int format = VIDEO_PIXFMT_BGRA;
#endif
        const auto bytes = videoFrameSize(format, width, height);

        if (bytes > 0) {
            if (auto buffer_ptr = target_.pull(bytes)) {
                buffer_ptr->format = libav_utils::libav_pixel_format(format);
                buffer_ptr->width = width;
                buffer_ptr->height = height;
                dst.setFromMemory(buffer_ptr->ptr, format, width, height);
                scaler_->scale(f, dst);
                target_.push(std::move(buffer_ptr));
            }
        }
    }
}
示例#6
0
    inline bool retry_for(
        const std::chrono::duration<Rep, Period>& total_time,
        const std::chrono::duration<Rep, Period>& time_step,
        std::function<bool (void)> retried_func) {
      assert(time_step.count()!=0);
      assert(total_time.count() >= time_step.count());

      size_t iterations = total_time.count() / time_step.count();
      for(size_t p=0; p <iterations; p++) {
        if(retried_func()) { return true; }
        std::this_thread::sleep_for(time_step);
      }
      return false;
    }
示例#7
0
FutureReturnCode
spin_node_until_future_complete(
  rclcpp::executor::Executor & executor, rclcpp::node::Node::SharedPtr node_ptr,
  std::shared_future<ResponseT> & future,
  std::chrono::duration<int64_t, TimeT> timeout = std::chrono::duration<int64_t, TimeT>(-1))
{
  // TODO(wjwwood): does not work recursively right, can't call spin_node_until_future_complete
  // inside a callback executed by an executor.

  // Check the future before entering the while loop.
  // If the future is already complete, don't try to spin.
  std::future_status status = future.wait_for(std::chrono::seconds(0));

  auto start_time = std::chrono::system_clock::now();

  while (status != std::future_status::ready && rclcpp::utilities::ok()) {
    executor.spin_node_once(node_ptr, timeout);
    if (timeout.count() >= 0) {
      if (start_time + timeout < std::chrono::system_clock::now()) {
        return TIMEOUT;
      }
    }
    status = future.wait_for(std::chrono::seconds(0));
  }

  // If the future completed, and we weren't interrupted by ctrl-C, return the response
  if (status == std::future_status::ready) {
    return FutureReturnCode::SUCCESS;
  }
  return FutureReturnCode::INTERRUPTED;
}
示例#8
0
// This gets called while rendering frame data is loading into GPU
// Good time to update measurements and physics before rendering next frame!
bool App::frameRenderingQueued(const Ogre::FrameEvent& evt) 
{
	//calculate delay and show
	delay = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - last_request);
	frames_per_second(delay.count());

	if (mShutdown) return false;

	if(mRift)
	{
		if ( mRift->update( evt.timeSinceLastFrame ) )
		{
			mScene->setRiftPose( mRift->getOrientation(), mRift->getPosition() );
		} else {
			delete mRift;
			mRift = NULL;
		}
	}

	//update the standard input devices
	mKeyboard->capture();
	mMouse->capture();

	//call updates on scene elements
	mScene->update( evt.timeSinceLastFrame );

	//get now time
	last_request = std::chrono::system_clock::now();

	//exit if key ESCAPE pressed 
	if(mKeyboard->isKeyDown(OIS::KC_ESCAPE)) 
		return false;

	return true; 
}
	_cv_status wait_for(std::unique_lock<std::mutex>& lock, const std::chrono::duration<Rep, Period>& rel_time)
	{
		if (rel_time.count() < 0)
		{
			return std::cv_status::timeout;
		}

		duration dur = std::chrono::duration_cast<duration>(rel_time);
		if (dur.count() == 0 && rel_time.count() != 0)
		{
			// don't do zero wait if non-zero wait was requested
			dur = duration(1);
		}

		return wait_for_impl(lock, dur);
	}
示例#10
0
int main(int argc, char* argv[]){
    nome_programa = argv[0];
    if(argc == 1) uso();
    else configura(argc, argv);

    /*-------------------
      Solovay-Strassen
    -------------------*/
    if(SS && !MR && !BPSW){
        if(!quiet){
            std::cout << "Solovay-Strassen -- Contagem de Tempo: ";
            tempo ? std::cout << "ativada.\n" : std::cout << "desativada.\n";
        }

        while(std::cin >> n >> k){
            tempo_decorrido = std::chrono::steady_clock::duration::zero();
            inicio = std::chrono::steady_clock::now();
            teste = solovay_strassen(n, k);
            fim = std::chrono::steady_clock::now();
            if(teste) std::cout << n << " e provavelmente primo.";
            else std::cout << n << " e composto.";
            if(tempo){
                tempo_decorrido = std::chrono::duration_cast<std::chrono::duration<double>>(fim - inicio);
                std::cout << " Tempo de execucao: " << tempo_decorrido.count();
            }
            std::cout << std::endl;
        }
    }

    /*----------------
        Miller-Rabin
    ----------------*/
    else if(!SS && MR && !BPSW){
示例#11
0
void CocoDeviceWrapper::tick()
{
	if(video)
	{
		glClearColor(0.0, 0.0, 0.0, 1.0);
		glClear(GL_COLOR_BUFFER_BIT);
		glwrap->SwapBuffers();
		return;
	}
	static size_t count = 0;
	static double total = 0.0;
	static std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
    static std::chrono::steady_clock::time_point now, last_tick = std::chrono::steady_clock::now(), last_draw = std::chrono::steady_clock::now();
    static std::chrono::duration<double, std::milli> tick_dif = std::chrono::duration<double, std::milli>::zero();
    static std::chrono::duration<double, std::milli> draw_dif = std::chrono::duration<double, std::milli>::zero();

    // Mark time and calc difference since last call
    now = std::chrono::steady_clock::steady_clock::now();
    draw_dif = now - last_draw;
    tick_dif = now - last_tick;

    // If the time ellapsed is grater than 16ms we flush OpenGL trying to achieve 60 fps.
    if((draw_dif + tick_dif).count() > 16.0)
    {
        last_draw = now;
        if(glwrap)
        {
        	double td = std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(now - start).count();
        	#ifdef __XMLHTTPREQUEST_HPP__
        	XMLHttpRequest::tick();
        	#endif
        	engine->run(td);
        	glwrap->SwapBuffers();
        	if(count++ == 30)
        	{
        		count = 1;
        		total = draw_dif.count();
        	} else total += draw_dif.count();
        }

        now = std::chrono::steady_clock::steady_clock::now();
    }
    last_tick = now;
}
示例#12
0
文件: picam.cpp 项目: Roboy/legs
void CameraCallback(CCamera* cam, const void* buffer, int buffer_length)
{
	// check ellapsed time and increment fps as long as the the frame is received withthin the specified interval 
	t2 = std::chrono::high_resolution_clock::now();
        time_span = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);    	
	if(time_span.count() < 10 ){
		fps += 1;
	}else{
		printf("fps: %f\n", fps/time_span.count());
		startMilliSecondTimer();
		fps = 0;	
	}
	//printf("Ellapsed time: %.3f received %d bytes of data\n", time_span.count, buffer_length);
	cv::Mat myuv(HEIGHT + HEIGHT/2, WIDTH, CV_8UC1, (unsigned char*)buffer);
	cv::Mat mrgb(HEIGHT, WIDTH, CV_8UC4, dest);
	cv::cvtColor(myuv, mrgb, CV_YUV2RGBA_NV21); 
	//cv::imshow("video", mrgb);
	//cv::waitKey(1);
}
示例#13
0
文件: main.cpp 项目: G4m4/ZenGarden
int main(int argc, char * const argv[]) {
  const int blockSize = 64;
  const int numInputChannels = 2;
  const int numOutputChannels = 2;
  const float sampleRate = 22050.0f;
  
  // pass directory and filename of the patch to load
  PdContext *context = zg_context_new(numInputChannels, numOutputChannels, blockSize, sampleRate,
      callbackFunction, NULL);
  
  // create a graph from a file
  
  PdGraph *graph = zg_context_new_graph_from_file(context, "/Users/mhroth/workspace/ZenGarden/demo/", "echolon_test0.pd");
  if (graph == NULL) {
    zg_context_delete(context);
    return 1;
  }
  
  /*
  // create a graph manually
  PdGraph *graph = zg_context_new_empty_graph(context);
  ZGObject *objOsc = zg_graph_add_new_object(graph, "osc~ 440", 0.0f, 0.0f);
  ZGObject *objDac = zg_graph_add_new_object(graph, "dac~", 0.0f, 0.0f);
  zg_graph_add_connection(graph, objOsc, 0, objDac, 0);
  zg_graph_add_connection(graph, objOsc, 0, objDac, 1);
  */
  // attach the graph
  zg_graph_attach(graph);
  
  float *inputBuffers = (float *) calloc(numInputChannels * blockSize, sizeof(float));
  float *outputBuffers = (float *) calloc(numOutputChannels * blockSize, sizeof(float));

  const auto start = std::chrono::high_resolution_clock::now();

  for (int i = 0; i < NUM_ITERATIONS; i++) {
  //while (1) {
    zg_context_process(context, inputBuffers, outputBuffers);
  }

  const auto end = std::chrono::high_resolution_clock::now();
  const std::chrono::duration<double> elapsedTimeSeconds = (end - start);  // seconds
  const double elapsedTime(elapsedTimeSeconds.count() * 1000.0);  // milliseconds
  printf("Runtime is: %i iterations in %f milliseconds == %f iterations/second.\n", NUM_ITERATIONS,
    elapsedTime, ((double) NUM_ITERATIONS)*1000.0/elapsedTime);
  const double simulatedTime = ((double)blockSize / (double)sampleRate) * (double)NUM_ITERATIONS * 1000.0; // milliseconds
  printf("Runs in realtime: %s (x%.3f)\n", (simulatedTime >= elapsedTime) ? "YES" : "NO", simulatedTime/elapsedTime);
  
  zg_context_delete(context);
  free(inputBuffers);
  free(outputBuffers);
  
  return 0;
}
示例#14
0
double IS::GetMOPS(std::chrono::duration<double> total_time,int niter,int num_keys)
{
	double mops = 0.0;

	double tt = total_time.count();

	if( tt > 0 )
	{
		mops = (double) niter+num_keys;
		mops *= niter / (tt*1000000.0);
	}

	return mops;
}
示例#15
0
void dynamic_matrix::assemble_mass()
{
    M.resize(mesh.active_dofs(), mesh.active_dofs());

    std::vector<doublet<int>> doublets;
    doublets.reserve(mesh.active_dofs());

    for (auto const& submesh : mesh.meshes())
    {
        for (std::int64_t element = 0; element < submesh.elements(); element++)
        {
            auto const dof_view = submesh.local_dof_view(element);

            for (std::int64_t p{0}; p < dof_view.size(); ++p)
            {
                for (std::int64_t q{0}; q < dof_view.size(); ++q)
                {
                    doublets.emplace_back(dof_view(p), dof_view(q));
                }
            }
        }
    }
    M.setFromTriplets(doublets.begin(), doublets.end());

    doublets.clear();

    auto const start = std::chrono::steady_clock::now();

    for (auto const& submesh : mesh.meshes())
    {
        for (std::int64_t element = 0; element < submesh.elements(); ++element)
        {
            auto const& [dofs, m] = submesh.consistent_mass(element);

            for (std::int64_t a{0}; a < dofs.size(); a++)
            {
                for (std::int64_t b{0}; b < dofs.size(); b++)
                {
                    M.add_to(dofs(a), dofs(b), m(a, b));
                }
            }
        }
    }

    auto const end = std::chrono::steady_clock::now();
    std::chrono::duration<double> const elapsed_seconds = end - start;

    std::cout << std::string(6, ' ') << "Mass assembly took " << elapsed_seconds.count() << "s\n";
}
示例#16
0
void SHMSink::render_frame(VideoFrame& src)
{
    VideoFrame dst;
    VideoScaler scaler;

    const int width = src.getWidth();
    const int height = src.getHeight();
    const int format = VIDEO_PIXFMT_BGRA;
    size_t bytes = dst.getSize(width, height, format);

    shm_lock();

    if (!resize_area(sizeof(SHMHeader) + bytes)) {
        ERROR("Could not resize area");
        return;
    }

    dst.setDestination(shm_area_->data, width, height, format);
    scaler.scale(src, dst);

#ifdef DEBUG_FPS
    const std::chrono::time_point<std::chrono::system_clock> currentTime = std::chrono::system_clock::now();
    const std::chrono::duration<double> seconds = currentTime - lastFrameDebug_;
    frameCount_++;
    if (seconds.count() > 1) {
        DEBUG("%s: FPS %f", shm_name_.c_str(), frameCount_ / seconds.count());
        frameCount_ = 0;
        lastFrameDebug_ = currentTime;
    }
#endif

    shm_area_->buffer_size = bytes;
    shm_area_->buffer_gen++;
    sem_post(&shm_area_->notification);
    shm_unlock();
}
示例#17
0
int main( int argc, char **argv ) {
    if( argc < 2 ) {
        cerr << "Usage: " << argv[0] << " [FILE]" << endl;
        return 0;
    }

    ifstream ifs(argv[1], ifstream::in);
    if(! ifs.good() ) {
        cerr << "Unable to open " << argv[1] << endl;
        return 0;
    }

    const int num_tests = 10;
    string line;
    string val;
    int N = 100000;
    while( getline( ifs, line ) ) {
        vector<int> incr;
        stringstream ss;
        ss << line;
        while( getline( ss, val, ',' ) ) {
            int v = stoi( val );
            if( v < 1 ) {
                cerr << "Error reading input file" << endl;
                return 0;
            }
            incr.push_back( v );
        }

        cout << "Using increments: " << line << endl;
        total_time = std::chrono::steady_clock::duration::zero();

        cout << "N = " << N << endl;
        for( int i = 0; i < num_tests; ++i ) {
            vector<int> vec( N );
            generate( vec.begin(), vec.end(), [&]() {
                return ( rand() % 6*N ) - 3*N;
            } );
            ShellSort::Sort( vec, incr );
        }
        cout << "Average: " << total_time.count() / num_tests << endl;
        cout << "------------------------------------" << endl;
        N += 100000;
    }
    return 0;
}
示例#18
0
void
ManualTimeKeeper::adjustCloseTime(
    std::chrono::duration<std::int32_t> amount)
{
    // Copied from TimeKeeper::adjustCloseTime
    using namespace std::chrono;
    auto const s = amount.count();
    std::lock_guard<std::mutex> lock(mutex_);
    // Take large offsets, ignore small offsets,
    // push the close time towards our wall time.
    if (s > 1)
        closeOffset_ += seconds((s + 3) / 4);
    else if (s < -1)
        closeOffset_ += seconds((s - 3) / 4);
    else
        closeOffset_ = (closeOffset_ * 3) / 4;
}
示例#19
0
 bool print(Iterator& out, std::chrono::duration<Rep, Period> d) const {
   using namespace printers;
   if (adaptive) {
     auto cnt = d.count();
     if (cnt > 1000000000)
       return detail::print_numeric(out, cnt / 1000000000)
              && any.print(out, '.')
              && detail::print_numeric(out, (cnt % 1000000000) / 10000000)
              && any.print(out, 's');
     if (cnt > 1000000)
       return detail::print_numeric(out, cnt / 1000000) && any.print(out, '.')
              && detail::print_numeric(out, (cnt % 1000000) / 10000)
              && str.print(out, "ms");
     if (cnt > 1000)
       return detail::print_numeric(out, cnt / 1000) && str.print(out, "us");
     return detail::print_numeric(out, cnt) && str.print(out, "ns");
   }
   auto secs = time::duration_cast<time::double_seconds>(d);
   return printers::real.print(out, secs.count()) && any.print(out, 's');
 }
示例#20
0
文件: main.cpp 项目: dustpg/NoteFL
int main() {
    test::a a;
    const auto call = [&a](std::size_t len, int index) noexcept {
        for(size_t i = 0; i != len; ++ i) a.ary[index]++;
    };
    constexpr size_t count = 20'0000'0000ll;

    const auto t0 = std::chrono::system_clock::now();

    std::thread thread{ call, count, test::len };

    std::function<void(std::size_t len, int index)>{ call } (count, 0);

    thread.join();

    const auto t1 = std::chrono::system_clock::now();

    const std::chrono::duration<double> d0 = t1 - t0;

    std::printf("time: +%lfs\n", d0.count());
    std::getchar();
    return 0;
}
    void computeStatistics(std::chrono::duration<float, std::milli> sampleDurationMilli)
    {
        const float sampleDurationSeconds= sampleDurationMilli.count() / 1000.f;
        const float N = static_cast<float>(sample_count);

        // Compute the mean of the error samples, where "error" = abs(omega_sample)
        // If we took the mean of the signed omega samples we'd get a value very 
        // close to zero since the the gyro at rest over a short period has mean-zero noise
        PSMVector3f mean_omega_error= *k_psm_float_vector3_zero;
        for (int sample_index = 0; sample_index < sample_count; sample_index++)
        {
            PSMVector3f error_sample= PSM_Vector3fAbs(&omega_samples[sample_index]);

            mean_omega_error= PSM_Vector3fAdd(&mean_omega_error, &error_sample);
        }
        mean_omega_error= PSM_Vector3fUnsafeScalarDivide(&mean_omega_error, N);

        // Compute the variance of the (unsigned) sample error, where "error" = abs(omega_sample)
        PSMVector3f var_omega= *k_psm_float_vector3_zero;
        for (int sample_index = 0; sample_index < sample_count; sample_index++)
        {
            PSMVector3f error_sample= PSM_Vector3fAbs(&omega_samples[sample_index]);
            PSMVector3f diff_from_mean= PSM_Vector3fSubtract(&error_sample, &mean_omega_error);
            PSMVector3f diff_from_mean_sqrd= PSM_Vector3fSquare(&diff_from_mean);

            var_omega= PSM_Vector3fAdd(&var_omega, &diff_from_mean);
        }
        var_omega= PSM_Vector3fUnsafeScalarDivide(&var_omega, N - 1);

        // Use the max variance of all three axes (should be close)
        variance= PSM_Vector3fMaxValue(&var_omega);

        // Compute the max drift rate we got across a three axis
        PSMVector3f drift_rate= PSM_Vector3fUnsafeScalarDivide(&drift_rotation, sampleDurationSeconds);
        PSMVector3f drift_rate_abs= PSM_Vector3fAbs(&drift_rate);
        drift= PSM_Vector3fMaxValue(&drift_rate_abs);
    }
示例#22
0
std::string short_time_format(std::chrono::duration<long long, std::pico> duration)
{
	char buff[16];

	unsigned long long millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
	unsigned long long micros = std::chrono::duration_cast<std::chrono::microseconds>(duration).count();
	unsigned long long nanoss = std::chrono::duration_cast<std::chrono::nanoseconds >(duration).count();
	unsigned long long picos = duration.count();

	     if (millis >= 100) sprintf(buff, "%4lldms", millis);
	else if (millis >=  10) sprintf(buff, "%2.1fms", static_cast<double>(micros) / 1000.0);
	else if (millis >=   1) sprintf(buff, "%1.2fms", static_cast<double>(micros) / 1000.0);
	else if (micros >= 100) sprintf(buff, "%4lldus", micros);
	else if (micros >=  10) sprintf(buff, "%2.1fus", static_cast<double>(nanoss) / 1000.0);
	else if (micros >=   1) sprintf(buff, "%1.2fus", static_cast<double>(nanoss) / 1000.0);
	else if (nanoss >= 100) sprintf(buff, "%4lldns", nanoss);
	else if (nanoss >=  10) sprintf(buff, "%2.1fns", static_cast<double>(picos) / 1000.0);
	else if (nanoss >=   1) sprintf(buff, "%1.2fns", static_cast<double>(picos) / 1000.0);
	else if (picos        ) sprintf(buff, "%4lldps", picos);
	else
		sprintf(buff, "Error!");

	return std::string(buff);
}
示例#23
0
int main(int argc, char* argv[]) {

    // 1. parse arguments

    if (argc != 4) {
        print_help(argv[0]);
        return EXIT_FAILURE;
    }

    const std::string name  = argv[1];
    const int size       = std::atoi(argv[2]);
    const int count      = std::atoi(argv[3]);

    if (!is_name_valid(name)) {
        printf("Unknown function name '%s'.\n", name.c_str());
        return EXIT_FAILURE;
    }

    if (size <= 0) {
        printf("Size must be greater than 0.\n");
        return EXIT_FAILURE;
    }

    if (count <= 0) {
        printf("Iteration count must be greater than 0.\n");
        return EXIT_FAILURE;
    }

    // 2. initialize memory

    uint8_t* data = static_cast<uint8_t*>(malloc(size));
    if (data == nullptr) {
        printf("allocation failed");
        return EXIT_FAILURE;
    }

    for (int i=0; i < size; i++) {
        data[i] = i;
    }


    // 3. run the test

    size_t n = 0;
    size_t k = count;

    std::printf("running %-30s...", name.c_str());
    std::fflush(stdout);

    const auto t1 = std::chrono::high_resolution_clock::now();

    if (name == "lookup-8") {

        while (k-- > 0) {
            n += popcnt_lookup_8bit(data, size);
        }

    } else if (name == "lookup-64") {

        while (k-- > 0) {
            n += popcnt_lookup_64bit(data, size);
        }

    } else if (name == "bit-parallel") {

        while (k-- > 0) {
            n += popcnt_parallel_64bit_naive(data, size);
        }

    } else if (name == "bit-parallel-optimized") {

        while (k-- > 0) {
            n += popcnt_parallel_64bit_optimized(data, size);
        }
    } else if (name == "sse-bit-parallel") {

        while (k-- > 0) {
            n += popcnt_SSE_bit_parallel(data, size);
        }
    } else if (name == "sse-lookup") {

        while (k-- > 0) {
            n += popcnt_SSE_lookup(data, size);
        }
    } else if (name == "cpu") {

        while (k-- > 0) {
            n += popcnt_cpu_64bit(data, size);
        }
    } else if (name == "lookup-3") {

        while (k-- > 0) {
            n += popcnt_lookup3_8bit(data, size);
        }
    } else if (name == "lookup-4") {

        while (k-- > 0) {
            n += popcnt_lookup4_8bit(data, size);
        }
    } else if (name == "lookup-7") {

        while (k-- > 0) {
            n += popcnt_lookup7_8bit(data, size);
        }
    } else {
        assert(false && "wrong function name handling");
    }

    const auto t2 = std::chrono::high_resolution_clock::now();

    const std::chrono::duration<double> td = t2-t1;

    printf("reference result = %lu, time = %10.6f s\n", n, td.count());

    free(data);

    return EXIT_SUCCESS;
}
示例#24
0
 constexpr duration(std::chrono::duration<Rep, Period> d)
 : unit(get_time_unit_from_period<Period>()), count(d.count()) {
     static_assert(get_time_unit_from_period<Period>() != time_unit::none,
                   "only seconds, milliseconds or microseconds allowed");
 }
示例#25
0
	void tick(std::chrono::duration<float> d)
	{
		set_relative_location(
			{get_relative_location().x, get_relative_location().y + 5 * d.count()});
	}
示例#26
0
 //!
 duration(std::chrono::duration<int64_t, std::nano> cpy)
   : duration(cpy.count(), std::nano::den) {}
示例#27
0
std::string TestDuration::hoursString(std::chrono::duration<int32_t, std::ratio<3600>> dt)
{
	return std::to_string(dt.count());
}
示例#28
0
std::string TestDuration::minutesString(std::chrono::duration<int32_t, std::ratio<60>> dt)
{
	return std::to_string(dt.count());
}
示例#29
0
 constexpr duration(std::chrono::duration<Rep, std::ratio<60,1> > d)
 : unit(time_unit::seconds), count(d.count() * 60) { }
示例#30
0
std::string TestDuration::nanosString(std::chrono::duration<int32_t, std::nano> dt)
{
	return std::to_string(dt.count());
}