• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C++ Timer类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中Timer的典型用法代码示例。如果您正苦于以下问题:C++ Timer类的具体用法?C++ Timer怎么用?C++ Timer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Timer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: main

int main(){
	bool go_on = true;
	int c;
	char s[1000];
	int width = 100;
	int height = 20;
	int block;
	int next_block;
	int socket_num = -1;
	bool bool_change = true;
	bool bool_win = false;
	int mysock;
	int inputsock;
	WINDOW *win;
	Act act = single;
	/*	WINDOW *my_menu_win;
		MENU *my_menu;
		ITEM **my_items;

		printf("Choose a mode to play\n");
		printf("1. Create an online game\n");
		printf("2. Join an online game\n");
		printf( "3. Play sigle mode\n");
		cin >> c;
	 */
	initscr();
	start_color();
	cbreak(); // disable key buffering
	keypad(stdscr, TRUE);
	noecho(); // disable echoing keypad(stdscr, TRUE);

	mvaddstr(1,4,"Choose a mode to play");
	mvaddstr(3,4,"1.Create an online game");
	mvaddstr(4,4,"2.Join an online game");
	mvaddstr(5,4,"3.Play in sinlge mode");

	while(go_on){
		c = getch();
		switch(c){
			case '1':
				act = server;
				socket_set(mysock, inputsock);
				srand( time(NULL));
				go_on = false;
				break;

			case '2':
				act = client;
				socket_set(mysock);
				srand( time(NULL) + 5);
				go_on = false;
				break;

			case '3':
				srand( time(NULL));
				go_on = false;

				break;
			default:	
				break;
		}

	}
	clear();

	go_on = true;
	nodelay(stdscr, TRUE);
	AbstractBlock *ptrBlock;
	Container container(14, 20);
	Poisition last_poi;
	Timer time;

	block = rand() % RAND_NUM;
	while( go_on ){
		while( (c=getch()) == ERR && go_on){
			if(bool_change){
				next_block = rand() % RAND_NUM;
				switch(block){
					case 0:
						ptrBlock = new TBlock(container, act);
						ptrBlock->paint();
						break;
					case 1:
						ptrBlock = new LBlock(container, act);
						ptrBlock->paint();
						break;
					case 2:
						ptrBlock = new ZBlock(container, act);
						ptrBlock->paint();
						break;
					case 3:
						ptrBlock = new IBlock(container, act);
						ptrBlock->paint();
						break;
					case 4:
						ptrBlock = new RZBlock(container, act);
						ptrBlock->paint();
						break;
					case 5:
						ptrBlock = new OBlock(container, act);
//.........这里部分代码省略.........
开发者ID:dsuper,项目名称:Teris,代码行数:101,代码来源:main.cpp


示例2: dbEval

    bool dbEval(const string& dbName, BSONObj& cmd, BSONObjBuilder& result, string& errmsg) {
        BSONElement e = cmd.firstElement();
        uassert( 10046 ,  "eval needs Code" , e.type() == Code || e.type() == CodeWScope || e.type() == String );

        const char *code = 0;
        switch ( e.type() ) {
        case String:
        case Code:
            code = e.valuestr();
            break;
        case CodeWScope:
            code = e.codeWScopeCode();
            break;
        default:
            verify(0);
        }
        verify( code );

        if ( ! globalScriptEngine ) {
            errmsg = "db side execution is disabled";
            return false;
        }

        auto_ptr<Scope> s = globalScriptEngine->getPooledScope( dbName );
        ScriptingFunction f = s->createFunction(code);
        if ( f == 0 ) {
            errmsg = (string)"compile failed: " + s->getError();
            return false;
        }

        if ( e.type() == CodeWScope )
            s->init( e.codeWScopeScopeData() );
        s->localConnect( dbName.c_str() );

        BSONObj args;
        {
            BSONElement argsElement = cmd.getField("args");
            if ( argsElement.type() == Array ) {
                args = argsElement.embeddedObject();
                if ( edebug ) {
                    out() << "args:" << args.toString() << endl;
                    out() << "code:\n" << code << endl;
                }
            }
        }

        int res;
        {
            Timer t;
            res = s->invoke(f, &args, 0, cmdLine.quota ? 10 * 60 * 1000 : 0 );
            int m = t.millis();
            if ( m > cmdLine.slowMS ) {
                out() << "dbeval slow, time: " << dec << m << "ms " << dbName << endl;
                if ( m >= 1000 ) log() << code << endl;
                else OCCASIONALLY log() << code << endl;
            }
        }
        if ( res ) {
            result.append("errno", (double) res);
            errmsg = "invoke failed: ";
            errmsg += s->getError();
            return false;
        }

        s->append( result , "retval" , "return" );

        return true;
    }
开发者ID:Desartstudio,项目名称:mongo-nonx86,代码行数:68,代码来源:dbeval.cpp


示例3: error


//.........这里部分代码省略.........
    default:
        // Everything else, including UNKNOWN -- default to 8 bit
        bps = 8;
        sampformat = SAMPLEFORMAT_UINT;
        m_spec.set_format (TypeDesc::UINT8);
        break;
    }
    TIFFSetField (m_tif, TIFFTAG_BITSPERSAMPLE, bps);
    TIFFSetField (m_tif, TIFFTAG_SAMPLEFORMAT, sampformat);

    int photo = (m_spec.nchannels > 1 ? PHOTOMETRIC_RGB : PHOTOMETRIC_MINISBLACK);
    TIFFSetField (m_tif, TIFFTAG_PHOTOMETRIC, photo);

    // ExtraSamples tag
    if (m_spec.nchannels > 3) {
        bool unass = m_spec.get_int_attribute("oiio:UnassociatedAlpha", 0);
        short e = m_spec.nchannels-3;
        std::vector<unsigned short> extra (e);
        for (int c = 0;  c < e;  ++c) {
            if (m_spec.alpha_channel == (c+3))
                extra[c] = unass ? EXTRASAMPLE_UNASSALPHA : EXTRASAMPLE_ASSOCALPHA;
            else
                extra[c] = EXTRASAMPLE_UNSPECIFIED;
        }
        TIFFSetField (m_tif, TIFFTAG_EXTRASAMPLES, e, &extra[0]);
    }

    // Default to LZW compression if no request came with the user spec
    if (! m_spec.find_attribute("compression"))
        m_spec.attribute ("compression", "lzw");

    ImageIOParameter *param;
    const char *str = NULL;

    // Did the user request separate planar configuration?
    m_planarconfig = PLANARCONFIG_CONTIG;
    if ((param = m_spec.find_attribute("planarconfig", TypeDesc::STRING)) ||
        (param = m_spec.find_attribute("tiff:planarconfig", TypeDesc::STRING))) {
        str = *(char **)param->data();
        if (str && Strutil::iequals (str, "separate")) {
            m_planarconfig = PLANARCONFIG_SEPARATE;
            if (! m_spec.tile_width) {
                // I can only seem to make separate planarconfig work when
                // rowsperstrip is 1.
                TIFFSetField (m_tif, TIFFTAG_ROWSPERSTRIP, 1);
            }
        }
    }
    TIFFSetField (m_tif, TIFFTAG_PLANARCONFIG, m_planarconfig);

    // Automatically set date field if the client didn't supply it.
    if (! m_spec.find_attribute("DateTime")) {
        time_t now;
        time (&now);
        struct tm mytm;
        Sysutil::get_local_time (&now, &mytm);
        std::string date = Strutil::format ("%4d:%02d:%02d %2d:%02d:%02d",
                               mytm.tm_year+1900, mytm.tm_mon+1, mytm.tm_mday,
                               mytm.tm_hour, mytm.tm_min, mytm.tm_sec);
        m_spec.attribute ("DateTime", date);
    }

    // Write ICC profile, if we have anything
    const ImageIOParameter* icc_profile_parameter = m_spec.find_attribute(ICC_PROFILE_ATTR);
    if (icc_profile_parameter != NULL) {
        unsigned char *icc_profile = (unsigned char*)icc_profile_parameter->data();
        uint32 length = icc_profile_parameter->type().size();
        if (icc_profile && length)
            TIFFSetField (m_tif, TIFFTAG_ICCPROFILE, length, icc_profile);
    }

    if (Strutil::iequals (m_spec.get_string_attribute ("oiio:ColorSpace"), "sRGB"))
        m_spec.attribute ("Exif:ColorSpace", 1);

    // Deal with all other params
    for (size_t p = 0;  p < m_spec.extra_attribs.size();  ++p)
        put_parameter (m_spec.extra_attribs[p].name().string(),
                       m_spec.extra_attribs[p].type(),
                       m_spec.extra_attribs[p].data());

    std::vector<char> iptc;
    encode_iptc_iim (m_spec, iptc);
    if (iptc.size()) {
        iptc.resize ((iptc.size()+3) & (0xffff-3));  // round up
        TIFFSetField (m_tif, TIFFTAG_RICHTIFFIPTC, iptc.size()/4, &iptc[0]);
    }

    std::string xmp = encode_xmp (m_spec, true);
    if (! xmp.empty())
        TIFFSetField (m_tif, TIFFTAG_XMLPACKET, xmp.size(), xmp.c_str());
    
    TIFFCheckpointDirectory (m_tif);  // Ensure the header is written early
    m_checkpointTimer.start(); // Initialize the to the fileopen time
    m_checkpointItems = 0; // Number of tiles or scanlines we've written

    m_dither = (m_spec.format == TypeDesc::UINT8) ?
                    m_spec.get_int_attribute ("oiio:dither", 0) : 0;

    return true;
}
开发者ID:gmarcusm,项目名称:oiio,代码行数:101,代码来源:tiffoutput.cpp


示例4: TestIndexPerformance

/*
 * TestIndexPerformance() - Test driver for indices of a given type
 *
 * This function tests Insert and Delete performance together with
 * key scan
 */
static void TestIndexPerformance(const IndexType &index_type) {
  // This is where we read all values in and verify them
  std::vector<ItemPointer *> location_ptrs;

  // INDEX
  std::unique_ptr<index::Index> index(BuildIndex(false, index_type));

  // Parallel Test by default 1 Million key

  // Number of threads doing insert or delete
  size_t num_thread = 4;

  // Number of keys inserted by each thread
  size_t num_key = 1024 * 256;

  Timer<> timer;

  ///////////////////////////////////////////////////////////////////
  // Start InsertTest1
  ///////////////////////////////////////////////////////////////////

  timer.Start();

  // First two arguments are used for launching tasks
  // All remaining arguments are passed to the thread body
  LaunchParallelTest(num_thread, InsertTest1, index.get(), num_thread, num_key);

  // Perform garbage collection
  if (index->NeedGC() == true) {
    index->PerformGC();
  }

  index->ScanAllKeys(location_ptrs);
  EXPECT_EQ(num_thread * num_key, location_ptrs.size());
  location_ptrs.clear();

  timer.Stop();
  LOG_INFO("InsertTest1 :: Type=%s; Duration=%.2lf",
           IndexTypeToString(index_type).c_str(), timer.GetDuration());

  ///////////////////////////////////////////////////////////////////
  // Start DeleteTest1
  ///////////////////////////////////////////////////////////////////

  timer.Start();

  LaunchParallelTest(num_thread, DeleteTest1, index.get(), num_thread, num_key);

  // Perform garbage collection
  if (index->NeedGC() == true) {
    index->PerformGC();
  }

  index->ScanAllKeys(location_ptrs);
  EXPECT_EQ(0, location_ptrs.size());
  location_ptrs.clear();

  timer.Stop();
  LOG_INFO("DeleteTest1 :: Type=%s; Duration=%.2lf",
           IndexTypeToString(index_type).c_str(), timer.GetDuration());

  ///////////////////////////////////////////////////////////////////
  // Start InsertTest2
  ///////////////////////////////////////////////////////////////////

  timer.Start();

  LaunchParallelTest(num_thread, InsertTest2, index.get(), num_thread, num_key);

  // Perform garbage collection
  if (index->NeedGC() == true) {
    index->PerformGC();
  }

  index->ScanAllKeys(location_ptrs);
  EXPECT_EQ(num_thread * num_key, location_ptrs.size());
  location_ptrs.clear();

  timer.Stop();
  LOG_INFO("InsertTest2 :: Type=%s; Duration=%.2lf",
           IndexTypeToString(index_type).c_str(), timer.GetDuration());

  ///////////////////////////////////////////////////////////////////
  // Start DeleteTest2
  ///////////////////////////////////////////////////////////////////

  timer.Start();

  LaunchParallelTest(num_thread, DeleteTest2, index.get(), num_thread, num_key);

  // Perform garbage collection
  if (index->NeedGC() == true) {
    index->PerformGC();
  }
//.........这里部分代码省略.........
开发者ID:Michael-Tieying-Zhang,项目名称:peloton,代码行数:101,代码来源:index_performance_test.cpp


示例5: commit

        void commit( set<DiskLoc>* dupsToDrop,
                     CurOp* op,
                     bool mayInterrupt ) {

            Timer timer;

            IndexCatalogEntry* entry = _real->_btreeState;

            bool dupsAllowed = !entry->descriptor()->unique() ||
                ignoreUniqueIndex(entry->descriptor());
            bool dropDups = entry->descriptor()->dropDups() || inDBRepair;

            BtreeBuilder<V> btBuilder(dupsAllowed, entry);

            BSONObj keyLast;
            scoped_ptr<BSONObjExternalSorter::Iterator> i( _phase1.sorter->iterator() );

            // verifies that pm and op refer to the same ProgressMeter
            ProgressMeter& pm = op->setMessage("Index Bulk Build: (2/3) btree bottom up",
                                               "Index: (2/3) BTree Bottom Up Progress",
                                               _phase1.nkeys,
                                               10);

            while( i->more() ) {
                RARELY killCurrentOp.checkForInterrupt( !mayInterrupt );
                ExternalSortDatum d = i->next();

                try {
                    if ( !dupsAllowed && dropDups ) {
                        LastError::Disabled led( lastError.get() );
                        btBuilder.addKey(d.first, d.second);
                    }
                    else {
                        btBuilder.addKey(d.first, d.second);
                    }
                }
                catch( AssertionException& e ) {
                    if ( dupsAllowed ) {
                        // unknown exception??
                        throw;
                    }

                    if( e.interrupted() ) {
                        killCurrentOp.checkForInterrupt();
                    }

                    if ( ! dropDups )
                        throw;

                    /* we could queue these on disk, but normally there are very few dups,
                     * so instead we keep in ram and have a limit.
                    */
                    if ( dupsToDrop ) {
                        dupsToDrop->insert(d.second);
                        uassert( 10092,
                                 "too may dups on index build with dropDups=true",
                                 dupsToDrop->size() < 1000000 );
                    }
                }
                pm.hit();
            }
            pm.finished();
            op->setMessage("Index Bulk Build: (3/3) btree-middle",
                           "Index: (3/3) BTree Middle Progress");
            LOG(timer.seconds() > 10 ? 0 : 1 ) << "\t done building bottom layer, going to commit";
            btBuilder.commit( mayInterrupt );
            if ( btBuilder.getn() != _phase1.nkeys && ! dropDups ) {
                warning() << "not all entries were added to the index, probably some "
                          << "keys were too large" << endl;
            }
        }
开发者ID:Attnaorg,项目名称:mongo,代码行数:71,代码来源:btree_based_access_method.cpp


示例6: memcpy

void dd::GibbsSampling::learn(const int & n_epoch, const int & n_sample_per_epoch, 
                              const double & stepsize, const double & decay, 
                              const double reg_param, const double reg1_param,
                              const bool is_quiet){
			      //const std::string meta_file, const bool is_quiet){

  Timer t_total;

  double current_stepsize = stepsize;

  Timer t;
  int nvar = this->factorgraphs[0].n_var;
  int nnode = n_numa_nodes + 1;
  int nweight = this->factorgraphs[0].n_weight;

//  int num_sources_per_var[nvar];
//  for (int i = 0; i < nvar; i++) {
//    num_sources_per_var[i] = 1;
//  }
//  std::string full_feature_names[nvar];
//  int feature_values[nvar];
//  std::map<std::string, int*> feature_var_map;
//  std::map<std::string,int*>::iterator it;
//  int num_feature_names = 0;
//
//  std::cout<<"Opening file "<<meta_file<<std::endl;
//  std::ifstream myfile;
//  std::string data;
//  myfile.open (meta_file);
//  if (myfile.good()) {
//    while ( std::getline(myfile,data)) {
//      istringstream iss(data);
//      std::string temp;
//      std::getline(iss, temp, '\t');
//      int feature_id = std::stoi(temp, nullptr);
//      std::string table_name;
//      std::getline(iss, table_name, '\t');
//      std::string feature_data;
//      std::getline(iss, feature_data);
//      feature_data = feature_data.substr(1, feature_data.length() - 2);
//      temp = feature_data.substr(14 + feature_data.find("source_count\":"), feature_data.find(",feature_name") - feature_data.find("source_count\":") - 14 );
//      num_sources_per_var[feature_id] = std::stoi(temp, nullptr);
//      temp = feature_data.substr(13 + feature_data.find("feature_name:"), feature_data.find(",feature_value") - feature_data.find("feature_name:") - 13 );
//      full_feature_names[feature_id] = table_name + "." + temp;
//      temp = feature_data.substr(14 + feature_data.find("feature_value:"), feature_data.find("}") - feature_data.find("feature_value:") - 14 );
//      feature_values[feature_id] = (int)std::stod(temp, nullptr);
//      it = feature_var_map.find(full_feature_names[feature_id]);
//      if (it != feature_var_map.end()) {
//        int* arr = it;
//        arr[feature_values[feature_id]] = feature_id;
//      } else {
//        feature_var_map[full_feature_names[feature_id]] = new int[10]; // NOTE: Hardcoded, change later.
//      }
//      feature_var_map[full_feature_names[feature_id]] = ;
//      std::cout << feature_id << " -- " << table_name << " - " << full_feature_names[feature_id] << " ;; " << feature_values[feature_id] << " ,, " << num_sources_per_var[feature_id] << std::endl;
//    }
//  }
//  myfile.close();
  
  
  // single node samplers
  std::vector<SingleNodeSampler> single_node_samplers;
  for(int i=0;i<=n_numa_nodes;i++){
    single_node_samplers.push_back(SingleNodeSampler(&this->factorgraphs[i], 
      n_thread_per_numa, i, false, 0, learn_non_evidence));
  }

  std::unique_ptr<double[]> ori_weights(new double[nweight]);
  memcpy(ori_weights.get(), this->factorgraphs[0].infrs->weight_values, sizeof(double)*nweight);

  // learning epochs
  for(int i_epoch=0;i_epoch<n_epoch;i_epoch++){

    if (!is_quiet) {
      std::cout << std::setprecision(2) << "LEARNING EPOCH " << i_epoch * nnode <<  "~" 
        << ((i_epoch+1) * nnode) << "...." << std::flush;
    }

    t.restart();
    
    // set stepsize
    for(int i=0;i<nnode;i++){
      single_node_samplers[i].p_fg->stepsize = current_stepsize;
    }

    // performs stochastic gradient descent with sampling
    for(int i=0;i<nnode;i++){
      single_node_samplers[i].sample_sgd();
    }

    // wait the samplers to finish
    for(int i=0;i<nnode;i++){
      single_node_samplers[i].wait_sgd();
    }

    FactorGraph & cfg = this->factorgraphs[0];

    // sum the weights and store in the first factor graph
    // the average weights will be calculated and assigned to all factor graphs 
    for(int i=1;i<=n_numa_nodes;i++){
//.........这里部分代码省略.........
开发者ID:thodrek,项目名称:sampler,代码行数:101,代码来源:gibbs_sampling.cpp


示例7: dbEval

    bool dbEval(const string& dbName, BSONObj& cmd, BSONObjBuilder& result, string& errmsg) {
        BSONElement e = cmd.firstElement();
        uassert( 10046 ,  "eval needs Code" , e.type() == Code || e.type() == CodeWScope || e.type() == String );

        const char *code = 0;
        switch ( e.type() ) {
        case String:
        case Code:
            code = e.valuestr();
            break;
        case CodeWScope:
            code = e.codeWScopeCode();
            break;
        default:
            verify(0);
        }
        verify( code );

        if ( ! globalScriptEngine ) {
            errmsg = "db side execution is disabled";
            return false;
        }

        const string userToken = ClientBasic::getCurrent()->getAuthorizationSession()
                                                          ->getAuthenticatedUserNamesToken();
        auto_ptr<Scope> s = globalScriptEngine->getPooledScope( dbName, "dbeval" + userToken );
        ScriptingFunction f = s->createFunction(code);
        if ( f == 0 ) {
            errmsg = (string)"compile failed: " + s->getError();
            return false;
        }

        if ( e.type() == CodeWScope )
            s->init( e.codeWScopeScopeDataUnsafe() );
        s->localConnect( dbName.c_str() );

        BSONObj args;
        {
            BSONElement argsElement = cmd.getField("args");
            if ( argsElement.type() == Array ) {
                args = argsElement.embeddedObject();
                if ( edebug ) {
                    log() << "args:" << args.toString() << endl;
                    log() << "code:\n" << code << endl;
                }
            }
        }

        int res;
        {
            Timer t;
            res = s->invoke(f, &args, 0, storageGlobalParams.quota ? 10 * 60 * 1000 : 0);
            int m = t.millis();
            if (m > serverGlobalParams.slowMS) {
                log() << "dbeval slow, time: " << dec << m << "ms " << dbName << endl;
                if ( m >= 1000 ) log() << code << endl;
                else OCCASIONALLY log() << code << endl;
            }
        }
        if (res || s->isLastRetNativeCode()) {
            result.append("errno", (double) res);
            errmsg = "invoke failed: ";
            if (s->isLastRetNativeCode())
                errmsg += "cannot return native function";
            else
                errmsg += s->getError();
            return false;
        }

        s->append( result , "retval" , "__returnValue" );

        return true;
    }
开发者ID:PedroLai,项目名称:mongo,代码行数:73,代码来源:dbeval.cpp


示例8: log

    void SimpleRecordStoreV1::_compactExtent(OperationContext* txn,
                                             const DiskLoc diskloc,
                                             int extentNumber,
                                             RecordStoreCompactAdaptor* adaptor,
                                             const CompactOptions* compactOptions,
                                             CompactStats* stats ) {

        log() << "compact begin extent #" << extentNumber
              << " for namespace " << _ns << " " << diskloc;

        unsigned oldObjSize = 0; // we'll report what the old padding was
        unsigned oldObjSizeWithPadding = 0;

        Extent *e = _extentManager->getExtent( diskloc );
        e->assertOk();
        fassert( 17437, e->validates(diskloc) );

        {
            // the next/prev pointers within the extent might not be in order so we first
            // page the whole thing in sequentially
            log() << "compact paging in len=" << e->length/1000000.0 << "MB" << endl;
            Timer t;
            size_t length = e->length;

            touch_pages( reinterpret_cast<const char*>(e), length );
            int ms = t.millis();
            if( ms > 1000 )
                log() << "compact end paging in " << ms << "ms "
                      << e->length/1000000.0/t.seconds() << "MB/sec" << endl;
        }

        {
            log() << "compact copying records" << endl;
            long long datasize = 0;
            long long nrecords = 0;
            DiskLoc L = e->firstRecord;
            if( !L.isNull() ) {
                while( 1 ) {
                    Record *recOld = recordFor(L);
                    RecordData oldData = recOld->toRecordData();
                    L = getNextRecordInExtent(txn, L);

                    if ( compactOptions->validateDocuments && !adaptor->isDataValid( oldData ) ) {
                        // object is corrupt!
                        log() << "compact skipping corrupt document!";
                        stats->corruptDocuments++;
                    }
                    else {
                        unsigned dataSize = adaptor->dataSize( oldData );
                        unsigned docSize = dataSize;

                        nrecords++;
                        oldObjSize += docSize;
                        oldObjSizeWithPadding += recOld->netLength();

                        unsigned lenWHdr = docSize + Record::HeaderSize;
                        unsigned lenWPadding = lenWHdr;

                        switch( compactOptions->paddingMode ) {
                        case CompactOptions::NONE:
                            if ( _details->isUserFlagSet(Flag_UsePowerOf2Sizes) )
                                lenWPadding = quantizePowerOf2AllocationSpace(lenWPadding);
                            break;
                        case CompactOptions::PRESERVE:
                            // if we are preserving the padding, the record should not change size
                            lenWPadding = recOld->lengthWithHeaders();
                            break;
                        case CompactOptions::MANUAL:
                            lenWPadding = compactOptions->computeRecordSize(lenWPadding);
                            if (lenWPadding < lenWHdr || lenWPadding > BSONObjMaxUserSize / 2 ) {
                                lenWPadding = lenWHdr;
                            }
                            break;
                        }

                        CompactDocWriter writer( recOld, dataSize, lenWPadding );
                        StatusWith<DiskLoc> status = insertRecord( txn, &writer, false );
                        uassertStatusOK( status.getStatus() );
                        datasize += recordFor( status.getValue() )->netLength();

                        adaptor->inserted( dataFor( txn, status.getValue() ), status.getValue() );
                    }

                    if( L.isNull() ) {
                        // we just did the very last record from the old extent.  it's still pointed to
                        // by the old extent ext, but that will be fixed below after this loop
                        break;
                    }

                    // remove the old records (orphan them) periodically so our commit block doesn't get too large
                    bool stopping = false;
                    RARELY stopping = !txn->checkForInterruptNoAssert().isOK();
                    if( stopping || txn->recoveryUnit()->isCommitNeeded() ) {
                        *txn->recoveryUnit()->writing(&e->firstRecord) = L;
                        Record *r = recordFor(L);
                        txn->recoveryUnit()->writingInt(r->prevOfs()) = DiskLoc::NullOfs;
                        txn->recoveryUnit()->commitIfNeeded();
                        txn->checkForInterrupt();
                    }
                }
//.........这里部分代码省略.........
开发者ID:wshiadai,项目名称:mongo,代码行数:101,代码来源:record_store_v1_simple.cpp


示例9: main


//.........这里部分代码省略.........
        ctrl.enumCtrl.maxInfNorms[6] = 2;
        ctrl.enumCtrl.maxInfNorms[7] = 2;
        */

        const double startTime = mpi::Time();
        Matrix<Real> R;
        auto info = BKZ( B, R, ctrl );
        const double runTime = mpi::Time() - startTime;
        Output
        ("  BKZ(",blocksize,",",delta,",",eta,") took ",runTime," seconds");
        Output("    achieved delta:   ",info.delta);
        Output("    achieved eta:     ",info.eta);
        Output("    num swaps:        ",info.numSwaps);
        Output("    num enums:        ",info.numEnums);
        Output("    num failed enums: ",info.numEnumFailures);
        Output("    log(vol(L)):      ",info.logVol);
        const Real GH = LatticeGaussianHeuristic( info.rank, info.logVol );
        const Real challenge = targetRatio*GH;
        Output("    GH(L):             ",GH);
        Output("    targetRatio*GH(L): ",challenge);
        if( print )
        {
            Print( B, "B" );
            Print( R, "R" );
        }
        Write( B, outputBasisFile, ASCII, "BKZ" );
        const Real BOneNorm = OneNorm( B );
        Output("|| B ||_1 = ",BOneNorm);

        auto b0 = B( ALL, IR(0) );
        const Real b0Norm = FrobeniusNorm( b0 );
        Output("|| b_0 ||_2 = ",b0Norm);
        if( print )
            Print( b0, "b0" );
        bool succeeded = false;
        if( b0Norm <= challenge )
        {
            Output
            ("SVP Challenge solved via BKZ: || b_0 ||_2=",b0Norm,
             " <= targetRatio*GH(L)=",challenge);
            succeeded = true;
            Write( b0, shortestVecFile, ASCII, "b0" );
        }
        else
            Output
            ("SVP Challenge NOT solved via BKZ: || b_0 ||_2=",b0Norm,
             " > targetRatio*GH(L)=",challenge);

        if( !succeeded || fullEnum )
        {
            const Int start = 0;
            const Int numCols = n;
            const Range<Int> subInd( start, start+numCols );
            auto BSub = B( ALL, subInd );
            auto RSub = R( subInd, subInd );

            const Real target = ( start == 0 ? challenge : RSub(0,0) );

            Timer timer;
            Matrix<F> v;
            EnumCtrl<Real> enumCtrl;
            enumCtrl.enumType = ( probEnum ? GNR_ENUM : FULL_ENUM );
            timer.Start();
            Real result;
            if( fullEnum )
            {
                result =
                  ShortestVectorEnumeration( BSub, RSub, target, v, enumCtrl );
                Output("shortest vector result = ",result);
            }
            else
            {
                result =
                  ShortVectorEnumeration( BSub, RSub, target, v, enumCtrl );
                Output("short vector result = ",result);
            }
            Output("Enumeration: ",timer.Stop()," seconds");
            if( result < target )
            {
                Print( BSub, "BSub" );
                Print( v, "v" );
                Matrix<Real> x;
                Zeros( x, m, 1 );
                Gemv( NORMAL, Real(1), BSub, v, Real(0), x );
                Print( x, "x" );
                const Real xNorm = FrobeniusNorm( x );
                Output("|| x ||_2 = ",xNorm);
                Output("Claimed || x ||_2 = ",result);
                Write( x, shortestVecFile, ASCII, "x" );

                EnrichLattice( BSub, v );
                Print( B, "BNew" );
            }
            else
                Output("Enumeration failed after ",timer.Stop()," seconds");
        }
    }
    catch( std::exception& e ) { ReportException(e); }
    return 0;
}
开发者ID:timmoon10,项目名称:Elemental,代码行数:101,代码来源:SVPChallenge.cpp


示例10: run

        void run() {

            try { boost::filesystem::remove(fn); }
            catch(...) { }

            Lock::GlobalWrite lk;

            {
                MongoMMF f;
                unsigned long long len = 256 * 1024 * 1024;
                verify( f.create(fn, len, /*sequential*/false) );
                {
                    char *p = (char *) f.getView();
                    verify(p);
                    // write something to the private view as a test
                    if( cmdLine.dur ) 
                        MemoryMappedFile::makeWritable(p, 6);
                    strcpy(p, "hello");
                }
                if( cmdLine.dur ) {
                    char *w = (char *) f.view_write();
                    strcpy(w + 6, "world");
                }
                MongoFileFinder ff;
                ASSERT( ff.findByPath(fn) );
                ASSERT( ff.findByPath("asdf") == 0 );
            }
            {
                MongoFileFinder ff;
                ASSERT( ff.findByPath(fn) == 0 );
            }

            int N = 10000;
#if !defined(_WIN32) && !defined(__linux__)
            // seems this test is slow on OS X.
            N = 100;
#endif

            // we make a lot here -- if we were leaking, presumably it would fail doing this many.
            Timer t;
            for( int i = 0; i < N; i++ ) {
                MongoMMF f;
                verify( f.open(fn, i%4==1) );
                {
                    char *p = (char *) f.getView();
                    verify(p);
                    if( cmdLine.dur ) 
                        MemoryMappedFile::makeWritable(p, 4);
                    strcpy(p, "zzz");
                }
                if( cmdLine.dur ) {
                    char *w = (char *) f.view_write();
                    if( i % 2 == 0 )
                        ++(*w);
                    verify( w[6] == 'w' );
                }
            }
            if( t.millis() > 10000 ) {
                log() << "warning: MMap LeakTest is unusually slow N:" << N << ' ' << t.millis() << "ms" << endl;
            }

        }
开发者ID:10genReviews,项目名称:mongo,代码行数:62,代码来源:mmaptests.cpp


示例11: main

int main(int argc, char* argv[])
{
	if (argc == 2)
	{
		//initiate variables
		unsigned char hash[20];
		char hexstr[41];
		unsigned int size = strlen(argv[1]);

		//convert to hash and then to string
		calc(argv[1], size, hash);
		toHexString(hash, hexstr);

		//print final string
		std::cout << hexstr << std::endl;
	}
	else if (argc == 3)
	{
		//check if files exist and open them
		std::ifstream dict(argv[1]);
		std::ifstream pass(argv[2]);
		if (pass.good() && dict.good())
		{
			//load dictionary
			HashMap dictTable = HashMap(dict);
			std::cout << dictTable.mNumElements << " elements added to table" << std::endl;
			std::cout << "Dictionary loaded in " << dictTable.mElapsed << " seconds." << std::endl;

			//open file for writing
			std::string line;
			std::ofstream solved;
			solved.open("pass_solved.txt");
			int count = 0;

			if (pass.is_open() && solved.is_open())
			{
				while (getline(pass, line))
				{
					dictTable.getPass(line, count);
					count++;
				}
				Timer timer;
				timer.start();
				tbb::parallel_invoke(
					[&dictTable] {dictTable.force(0, 4); },
					[&dictTable] {dictTable.force(4, 8); },
					[&dictTable] {dictTable.force(8, 12); },
					[&dictTable] {dictTable.force(12, 16); },
					[&dictTable] {dictTable.force(16, 20); },
					[&dictTable] {dictTable.force(20, 24); },
					[&dictTable] {dictTable.force(24, 28); },
					[&dictTable] {dictTable.force(28, 32); },
					[&dictTable] {dictTable.force(32, 36); });
				std::cout << "Passwords decrypted in " << timer.getElapsed() << " seconds" << std::endl;
				for (int i = 0; i < signed int(dictTable.mSolved.size()); i++)
				{
					try
					{
						solved << dictTable.mSolved.at(i)->mHexStr << "," << dictTable.mSolved.at(i)->mSolution << std::endl;
					}
					catch (const std::out_of_range& oor)
					{
						std::cerr << "Out of Range error: " << oor.what() << '\n';
					}
				}
			}
			else
			{
开发者ID:alexxgmurphy,项目名称:Password-Cracker,代码行数:68,代码来源:Main.cpp


示例12: REMAPPRIVATEVIEW

 /** We need to remap the private views periodically. otherwise they would become very large.
     Call within write lock.  See top of file for more commentary.
 */
 void REMAPPRIVATEVIEW() {
     Timer t;
     _REMAPPRIVATEVIEW();
     stats.curr->_remapPrivateViewMicros += t.micros();
 }
开发者ID:nosqldb,项目名称:mongo,代码行数:8,代码来源:dur.cpp


示例13: _REMAPPRIVATEVIEW

        static void _REMAPPRIVATEVIEW() {
            // todo: Consider using ProcessInfo herein and watching for getResidentSize to drop.  that could be a way 
            //       to assure very good behavior here.

            static unsigned startAt;
            static unsigned long long lastRemap;

            LOG(4) << "journal REMAPPRIVATEVIEW" << endl;

            verify( Lock::isW() );
            verify( !commitJob.hasWritten() );

            // we want to remap all private views about every 2 seconds.  there could be ~1000 views so
            // we do a little each pass; beyond the remap time, more significantly, there will be copy on write
            // faults after remapping, so doing a little bit at a time will avoid big load spikes on
            // remapping.
            unsigned long long now = curTimeMicros64();
            double fraction = (now-lastRemap)/2000000.0;
            if( cmdLine.durOptions & CmdLine::DurAlwaysRemap )
                fraction = 1;
            lastRemap = now;

#if defined(_WIN32)
            // Note that this negatively affects performance.
            // We must grab the exclusive lock here because remapThePrivateView() on Windows needs
            // to grab it as well, due to the lack of a non-atomic way to remap a memory mapped file.
            // See SERVER-5723 for performance improvement.
            // See SERVER-5680 to see why this code is necessary.
            LockMongoFilesExclusive lk;
#else
            LockMongoFilesShared lk;
#endif
            set<MongoFile*>& files = MongoFile::getAllFiles();
            unsigned sz = files.size();
            if( sz == 0 )
                return;

            {
                // be careful not to use too much memory if the write rate is 
                // extremely high
                double f = privateMapBytes / ((double)UncommittedBytesLimit);
                if( f > fraction ) { 
                    fraction = f;
                }
                privateMapBytes = 0;
            }

            unsigned ntodo = (unsigned) (sz * fraction);
            if( ntodo < 1 ) ntodo = 1;
            if( ntodo > sz ) ntodo = sz;

            const set<MongoFile*>::iterator b = files.begin();
            const set<MongoFile*>::iterator e = files.end();
            set<MongoFile*>::iterator i = b;
            // skip to our starting position
            for( unsigned x = 0; x < startAt; x++ ) {
                i++;
                if( i == e ) i = b;
            }
            unsigned startedAt = startAt;
            startAt = (startAt + ntodo) % sz; // mark where to start next time

            Timer t;
            for( unsigned x = 0; x < ntodo; x++ ) {
                dassert( i != e );
                if( (*i)->isMongoMMF() ) {
                    MongoMMF *mmf = (MongoMMF*) *i;
                    verify(mmf);
                    if( mmf->willNeedRemap() ) {
                        mmf->willNeedRemap() = false;
                        mmf->remapThePrivateView();
                    }
                    i++;
                    if( i == e ) i = b;
                }
            }
            LOG(2) << "journal REMAPPRIVATEVIEW done startedAt: " << startedAt << " n:" << ntodo << ' ' << t.millis() << "ms" << endl;
        }
开发者ID:nosqldb,项目名称:mongo,代码行数:78,代码来源:dur.cpp


示例14: trainModel

bool KMeans::trainModel(MatrixFloat &data){
    
    if( numClusters == 0 ){
        errorLog << "trainModel(MatrixFloat &data) - Failed to train model. NumClusters is zero!" << std::endl;
		return false;
	}
    
    if( clusters.getNumRows() != numClusters ){
        errorLog << "trainModel(MatrixFloat &data) - Failed to train model. The number of rows in the cluster matrix does not match the number of clusters! You should need to initalize the clusters matrix first before calling this function!" << std::endl;
		return false;
	}
    
    if( clusters.getNumCols() != numInputDimensions ){
        errorLog << "trainModel(MatrixFloat &data) - Failed to train model. The number of columns in the cluster matrix does not match the number of input dimensions! You should need to initalize the clusters matrix first before calling this function!" << std::endl;
		return false;
	}

    Timer timer;
	UINT currentIter = 0;
    UINT numChanged = 0;
	bool keepTraining = true;
    Float theta = 0;
    Float lastTheta = 0;
    Float delta = 0;
    Float startTime = 0;
    thetaTracker.clear();
    finalTheta = 0;
    numTrainingIterationsToConverge = 0;
    trained = false;
    converged = false;
    
    //Scale the data if needed
    ranges = data.getRanges();
    if( useScaling ){
        data.scale(0,1);
    }

    //Init the assign and count Vectors
    //Assign is set to K+1 so that the nChanged values in the eStep at the first iteration will be updated correctly
    for(UINT m=0; m<numTrainingSamples; m++) assign[m] = numClusters+1;
	for(UINT k=0; k<numClusters; k++) count[k] = 0;

    //Run the training loop
    timer.start();
	while( keepTraining ){
        startTime = timer.getMilliSeconds();

		//Compute the E step
		numChanged = estep( data );

        //Compute the M step
        mstep( data );

        //Update the iteration counter
		currentIter++;

		//Compute theta if needed
		if( computeTheta ){
            theta = calculateTheta(data);
            delta = lastTheta - theta;
            lastTheta = theta;
        }else theta = delta = 0;
        
        //Check convergance
		if( numChanged == 0 && currentIter > minNumEpochs ){ converged = true; keepTraining = false; }
		if( currentIter >= maxNumEpochs ){ keepTraining = false; }
		if( fabs( delta ) < minChange && computeTheta && currentIter > minNumEpochs ){ converged = true; keepTraining = false; }
        if( computeTheta )  thetaTracker.push_back( theta );
        
        trainingLog << "Epoch: " << currentIter << "/" << maxNumEpochs;
        trainingLog << " Epoch time: " << (timer.getMilliSeconds()-startTime)/1000.0 << " seconds";
        trainingLog << " Theta: " << theta << " Delta: " << delta << std::endl;
	}
    trainingLog << "Model Trained at epoch: " << currentIter << " with a theta value of: " << theta << std::endl;

    finalTheta = theta;
    numTrainingIterationsToConverge = currentIter;
	trained = true;
    
    //Setup the cluster labels
    clusterLabels.resize(numClusters);
    for(UINT i=0; i<numClusters; i++){
        clusterLabels[i] = i+1;
    }
    clusterLikelihoods.resize(numClusters,0);
    clusterDistances.resize(numClusters,0);
	
	return true;
}
开发者ID:CV-IP,项目名称:grt,代码行数:89,代码来源:KMeans.cpp


示例15: updateComponent

void NonLinearDynamic :: updateComponent(TimeStep *tStep, NumericalCmpn cmpn, Domain *d)
//
// Updates some component, which is used by numerical method
// to newly reached state. used mainly by numerical method
// when new tanget stiffness is needed during finding
// of new equlibrium stage.
//
{
#ifdef T 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ TimerInfoPtr类代码示例发布时间:2022-05-31
下一篇:
C++ TimeoutManager类代码示例发布时间:2022-05-31
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap