您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ time函数代码示例

51自学网 2021-06-03 08:50:13
  C++
这篇教程C++ time函数代码示例写得很实用,希望能帮到您。

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

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

示例1: Solution

  Solution(){     srand(time(NULL)); }
开发者ID:mandagod,项目名称:LeetCode,代码行数:3,


示例2: UpdateFilebase

VOID UpdateFilebase (USHORT KeepDate){   FILE *fp;   DIR *dir;   ULONG Total, Added;   CHAR *p, Path[128], Temp[128];   time_t today;   struct stat statbuf;   struct tm *ltm;   struct dirent *ent;   class TFileData *Data;   class TFileBase *File;   class TPacker *Packer;   printf (" * Updating filebase/r/n");   unlink ("file_id.diz");   Packer = new TPacker (Cfg->SystemPath);   if ((Data = new TFileData (Cfg->SystemPath)) != NULL) {      if (Data->First () == TRUE)         do {            Total = 0L;            Added = 0L;            cprintf (" +-- %-15.15s %-32.32s ", Data->Key, Data->Display);            if ((File = new TFileBase (Cfg->SystemPath, Data->Key)) != NULL) {               strcpy (Temp, Data->Download);               if (Temp[strlen (Temp) - 1] == '//' || Temp[strlen (Temp) - 1] == '/')                  Temp[strlen (Temp) - 1] = '/0';               if (File->First () == TRUE)                  do {                     sprintf (Path, "%s%s", Data->Download, File->Name);                     if (stat (AdjustPath (Path), &statbuf))                        File->Delete ();                  } while (File->Next () == TRUE);               File->SortByName ();               if ((dir = opendir (AdjustPath (Temp))) != NULL) {                  while ((ent = readdir (dir)) != NULL) {                     if (!strcmp (ent->d_name, ".") || !strcmp (ent->d_name, ".."))                        continue;                     if (!stricmp (ent->d_name, "files.bbs") || !stricmp (ent->d_name, "descript.ion"))                        continue;                     if (File->Read (ent->d_name) == FALSE) {                        sprintf (Path, "%s%s", Data->Download, ent->d_name);                        if (!stat (AdjustPath (Path), &statbuf)) {                           File->Clear ();                           strcpy (File->Area, Data->Key);                           strcpy (File->Name, ent->d_name);                           strcpy (File->Complete, Path);                           File->Size = statbuf.st_size;                           ltm = localtime ((time_t *)&statbuf.st_mtime);                           File->Date.Day = (UCHAR)ltm->tm_mday;                           File->Date.Month = (UCHAR)(ltm->tm_mon + 1);                           File->Date.Year = (USHORT)(ltm->tm_year + 1900);                           File->Date.Hour = (UCHAR)ltm->tm_hour;                           File->Date.Minute = (UCHAR)ltm->tm_min;                           if (KeepDate == FALSE) {                              today = time (NULL);                              ltm = localtime (&today);                              File->UplDate.Day = (UCHAR)ltm->tm_mday;                              File->UplDate.Month = (UCHAR)(ltm->tm_mon + 1);                              File->UplDate.Year = (USHORT)(ltm->tm_year + 1900);                              File->UplDate.Hour = (UCHAR)ltm->tm_hour;                              File->UplDate.Minute = (UCHAR)ltm->tm_min;                           }                           else {                              File->UplDate.Day = File->Date.Day;                              File->UplDate.Month = File->Date.Month;                              File->UplDate.Year = File->Date.Year;                              File->UplDate.Hour = File->Date.Hour;                              File->UplDate.Minute = File->Date.Minute;                           }                           File->Uploader = "Sysop";                           File->CdRom = Data->CdRom;                           File->Description->Add ("Description missing");                           if (Packer != NULL) {                              if (Packer->CheckArc (Path) == TRUE) {#if defined(__LINUX__)                                 mkdir ("lfiletmp", 0666);#else                                 mkdir ("lfiletmp");#endif                                 if (strstr (Packer->UnpackCmd, "%3") == NULL && strstr (Packer->UnpackCmd, "%f") == NULL)                                    strcat (Packer->UnpackCmd, " %3");                                 Packer->DoUnpack (Path, "lfiletmp", "file_id.diz");                                 strcpy (Temp, "lfiletmp//file_id.diz");                                 if (!stat (AdjustPath (Temp), &statbuf)) {                                    if ((fp = fopen (Temp, "rt")) != NULL) {                                       File->Description->Clear ();                                       while (fgets (Temp, sizeof (Temp) - 1, fp) != NULL) {                                          if ((p = strchr (Temp, '/n')) != NULL)                                             *p = '/0';                                          if ((p = strchr (Temp, '/r')) != NULL)                                             *p = '/0';                                          File->Description->Add (Temp);                                       }                                       fclose (fp);                                    }//.........这里部分代码省略.........
开发者ID:kenjreno,项目名称:lora3,代码行数:101,


示例3: backup_compact

/* returns: *   0 on success *   1 if compact was not needed *   negative on error */EXPORTED int backup_compact(const char *name,                            enum backup_open_nonblock nonblock,                            int force, int verbose, FILE *out){    struct backup *original = NULL;    struct backup *compact = NULL;    struct backup_chunk_list *all_chunks = NULL;    struct backup_chunk_list *keep_chunks = NULL;    struct backup_chunk *chunk = NULL;    struct sync_msgid_list *keep_message_guids = NULL;    struct gzuncat *gzuc = NULL;    struct protstream *in = NULL;    time_t since, chunk_start_time, ts;    int r;    compact_readconfig();    r = compact_open(name, &original, &compact, nonblock);    if (r) return r;    /* calculate current time after obtaining locks, in case of a wait */    const time_t now = time(NULL);    const int retention_days = config_getint(IMAPOPT_BACKUP_RETENTION_DAYS);    if (retention_days > 0) {        since = now - (retention_days * 24 * 60 * 60);    }    else {        /* zero or negative retention days means "keep forever" */        since = -1;    }    all_chunks = backup_get_chunks(original);    if (!all_chunks) goto error;    keep_chunks = backup_get_live_chunks(original, since);    if (!keep_chunks) goto error;    if (!force && !compact_required(all_chunks, keep_chunks)) {        /* nothing to do */        backup_chunk_list_free(&all_chunks);        backup_chunk_list_free(&keep_chunks);        backup_unlink(&compact);        backup_close(&original);        return 1;    }    if (verbose) {        fprintf(out, "keeping " SIZE_T_FMT " chunks:/n", keep_chunks->count);        for (chunk = keep_chunks->head; chunk; chunk = chunk->next) {            fprintf(out, " %d", chunk->id);        }        fprintf(out, "/n");    }    gzuc = gzuc_new(original->fd);    if (!gzuc) goto error;    chunk_start_time = -1;    ts = 0;    struct buf cmd = BUF_INITIALIZER;    for (chunk = keep_chunks->head; chunk; chunk = chunk->next) {        keep_message_guids = sync_msgid_list_create(0);        r = backup_message_foreach(original, chunk->id, &since,                                   _keep_message_guids_cb, keep_message_guids);        if (r) goto error;        gzuc_member_start_from(gzuc, chunk->offset);        in = prot_readcb(_prot_fill_cb, gzuc);        while (1) {            struct dlist *dl = NULL;            int c = parse_backup_line(in, &ts, &cmd, &dl);            if (c == EOF) {                const char *error = prot_error(in);                if (error && 0 != strcmp(error, PROT_EOF_STRING)) {                    syslog(LOG_ERR,                           "IOERROR: %s: error reading chunk at offset %jd, byte %i: %s/n",                           name, chunk->offset, prot_bytes_in(in), error);                    if (out)                        fprintf(out, "error reading chunk at offset %jd, byte %i: %s/n",                                chunk->offset, prot_bytes_in(in), error);                    r = IMAP_IOERROR;                    goto error;                }                break;            }//.........这里部分代码省略.........
开发者ID:rsto,项目名称:cyrus-imapd,代码行数:101,


示例4: oneshot_cb

static void oneshot_cb (EV_P_ ev_timer *w, int revents){    printf("oneshot at %ju/n", (uintmax_t)time(NULL));    ev_timer_stop(EV_A_ w);}
开发者ID:jasonblog,项目名称:note,代码行数:5,


示例5: main

int main(int argc, char** argv) {	int i = 0, j = 0;	ull gen_size = 0, code_size = 0, data_size = 0;	ull blocks = 0, wordsize = 0, dim = 0;	unsigned char *G = NULL, *D = NULL, *DD = NULL, *C = NULL, *NC = NULL;	unsigned short *masks = NULL;	unsigned char *code_tmp = NULL, *data_block_tmp = NULL;	double accumulator = 0;	char buffer[100];	FILE *fout = NULL;		srand (time(NULL));	ull r = 0, m = 16, k = 50, max_iter = 700;	data_size = 4096;	char **ptr = NULL;		if (argc == 3) {		r = strtol(argv[1], ptr, 10);		m = strtol(argv[2], ptr, 10);	}	//rm_test_0(r, m, k, max_iter, stdout);	for (i = r; i < m; ++i) {		sprintf(buffer, "output_%2d", i);		fout = fopen(buffer, "w");		fprintf(fout, "%d/n", i);		for (j = 0; j <= i; ++j) {			printf("%d %d/n", i, j);			fprintf(fout, "%d %d/n", i, j);			rm_test_0(j, i, k, max_iter, fout);			fprintf(fout, "/n");		}		fclose(fout);	}	//rm_test_0(r, m, k, max_iter);	// //for (m = 12; m < 16; ++m) 	// {	// 	gen_size = generation_mem_size(m, m);	// 	G = (unsigned char *) malloc(gen_size);	// 	generate_matrix(m, m, G);	// 	masks = (unsigned short *) malloc((1 << m) * sizeof(unsigned short));	// 	generate_masks(m, masks);	// 	// for (r = 0; r <= m; ++r) 	// 	{					// 		D =	(unsigned char *) malloc(data_size);	// 		DD = (unsigned char *) malloc(data_size);	// 		for (int i = 0; i < data_size; ++i)	// 			D[i] = (unsigned char) rand();		     				// 		code_size = encode_mem_size(data_size, r, m);	// 		C = (unsigned char *) malloc(code_size);	// 		NC = (unsigned char *) malloc(code_size);	// 		encode(r, m, G, data_size, D, C, masks);				// 		blocks = rm_blocks(data_size, r, m);	// 		wordsize = rm_wordsize(r, m);	// 		dim = rm_dim(r, m);	// 		code_tmp = (unsigned char *) malloc(wordsize / 8 + (wordsize % 8 == 0 ? 0 : 1));	// 		data_block_tmp = (unsigned char *) malloc(dim / 8 + (dim % 8 == 0 ? 0 : 1));	// 		decode(r, m, G, data_size, DD, C, masks, code_tmp, data_block_tmp);	// 		// print(1, 8 * data_size, D);//printf("/n");	// 		// print(1, 8 * data_size, DD);printf("/n/n");	// 		//printf("r = %d, m = %d/n", r, m);	// 		//printf("/nAccuracy %1.9lf:/n/n", accuracy(data_size, D, DD));	// 		for (ull i = 0; i <= k; i++) {	// 			accumulator = 0;	// 			printf("%1.9lf ", (double) i / (double) k);	// 			for (ull j = 0; j < max_iter; ++j) {	// 				memcpy(NC, C, code_size);	// 				add_noise(NC, code_size, (double) i / (double) k);		// 				decode(r, m, G, data_size, DD, NC, masks, code_tmp, data_block_tmp);	// 				accumulator += accuracy(data_size, dim, D, DD);	// 			}	// 			printf("%1.9lf /n", accumulator / max_iter);	// 		}	// 		FREE_IF_ALLOCATED(C);	// 		FREE_IF_ALLOCATED(D);//.........这里部分代码省略.........
开发者ID:sergeykhegay,项目名称:university_projects,代码行数:101,


示例6: rearm

static void rearm(time_t *timer, int seconds){	time(timer);	*timer += seconds;}
开发者ID:louisdem,项目名称:IMKit,代码行数:5,


示例7: timeout_cb

// another callback, this time for a time-outstatic void timeout_cb (EV_P_ ev_timer *w, int revents){    printf("timeout at %ju/n", (uintmax_t)time(NULL));    // this causes the innermost ev_run to stop iterating    ev_break (EV_A_ EVBREAK_ONE);}
开发者ID:jasonblog,项目名称:note,代码行数:7,


示例8: default_log_handler

/* internal log handler function */static int default_log_handler(log_level_t level,const char *fmt, va_list args) {    time_t epoch;    time(&epoch);    return _log_vfprintf(log_out, &epoch, LEVEL_EVENTS[level], fmt, args);}
开发者ID:dvandok,项目名称:argus-pep-api-c,代码行数:6,


示例9: getEpochTime

 static int getEpochTime() {     return (unsigned int)time(NULL); }
开发者ID:Bewolf2,项目名称:LoomSDK,代码行数:4,


示例10: main

int main(int argc, char **argv){  float *Hydrograph = NULL;  float ***MM5Input = NULL;  float **PrecipLapseMap = NULL;  float **PrismMap = NULL;  unsigned char ***ShadowMap = NULL;  float **SkyViewMap = NULL;  float ***WindModel = NULL;  int MaxStreamID, MaxRoadID;  float SedDiams[NSEDSIZES];     /* Sediment particle diameters (mm) */  clock_t start, finish1;  double runtime = 0.0;  int t = 0;  float roadarea;  time_t tloc;  int flag;  int i;  int j;  int x;						/* row counter */  int y;						/* column counter */  int shade_offset;				/* a fast way of handling arraay position given the number of mm5 input options */  int NStats;					/* Number of meteorological stations */  uchar ***MetWeights = NULL;	/* 3D array with weights for interpolating meteorological variables between the stations */  int NGraphics;				/* number of graphics for X11 */  int *which_graphics;			/* which graphics for X11 */  char buffer[32];  AGGREGATED Total = {			/* Total or average value of a  variable over the entire basin */    {0.0, NULL, NULL, NULL, NULL, 0.0},												/* EVAPPIX */    {0.0, 0.0, 0.0, 0.0, 0.0, NULL, NULL, 0.0, 0, 0.0},								/* PRECIPPIX */    {{0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, 0.0, 0.0, 0.0},							/* PIXRAD */    {0.0, 0.0},																		/* RADCLASSPIX */    {0.0, 0.0, 0, NULL, NULL, 0.0, 0, 0.0, 0.0, 0.0, 0.0, NULL, 	NULL, NULL, NULL, NULL, NULL, 0.0},												/* ROADSTRUCT*/    {0, 0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},		/* SNOWPIX */    {0, 0.0, NULL, NULL, NULL, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,     0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},			/*SOILPIX */    { 0.0, 0.0, 0.0, 0.0, 0.0},														/*SEDPIX */    { 0.0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},							/*FINEPIX */    0.0, 0.0, 0.0, 0.0, 0.0, 0l, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0  };  CHANNEL ChannelData = {NULL, NULL, NULL, NULL, NULL, NULL, NULL,   NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,  NULL, NULL, NULL, NULL};  DUMPSTRUCT Dump;  EVAPPIX **EvapMap = NULL;  INPUTFILES InFiles;  LAYER Soil;  LAYER Veg;  LISTPTR Input = NULL;			/* Linked list with input strings */  MAPSIZE Map;					/* Size and location of model area */  MAPSIZE Radar;				/* Size and location of area covered by precipitation radar */  MAPSIZE MM5Map;				/* Size and location of area covered by MM5 input files */  METLOCATION *Stat = NULL;  OPTIONSTRUCT Options;			/* Structure with information which program options to follow */  PIXMET LocalMet;				/* Meteorological conditions for current pixel */  FINEPIX ***FineMap	= NULL;  PRECIPPIX **PrecipMap = NULL;  RADARPIX **RadarMap	= NULL;  RADCLASSPIX **RadMap	= NULL;  PIXRAD **RadiationMap = NULL;  ROADSTRUCT **Network	= NULL;	/* 2D Array with channel information for each pixel */  SNOWPIX **SnowMap		= NULL;  MET_MAP_PIX **MetMap	= NULL;  SNOWTABLE *SnowAlbedo = NULL;  SOILPIX **SoilMap		= NULL;  SEDPIX **SedMap		= NULL;  SOILTABLE *SType	    = NULL;  SEDTABLE *SedType		= NULL;  SOLARGEOMETRY SolarGeo;		/* Geometry of Sun-Earth system (needed for INLINE radiation calculations */  TIMESTRUCT Time;  TOPOPIX **TopoMap = NULL;  UNITHYDR **UnitHydrograph = NULL;  UNITHYDRINFO HydrographInfo;	/* Information about unit hydrograph */  VEGPIX **VegMap = NULL;  VEGTABLE *VType = NULL;  WATERBALANCE Mass =			/* parameter for mass balance calculations */    { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,        0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };/*****************************************************************************  Initialization Procedures *****************************************************************************/  if (argc != 2) {    fprintf(stderr, "/nUsage: %s inputfile/n/n", argv[0]);    fprintf(stderr, "DHSVM uses two output streams: /n");    fprintf(stderr, "Standard Out, for the majority of output /n");    fprintf(stderr, "Standard Error, for the final mass balance /n");    fprintf(stderr, "/nTo pipe output correctly to files: /n");    fprintf(stderr, "(cmd > f1) >& f2 /n");    fprintf(stderr, "where f1 is stdout_file and f2 is stderror_file/n");    exit(EXIT_FAILURE);  }  sprintf(commandline, "%s %s", argv[0], argv[1]);  printf("%s /n", commandline);  fprintf(stderr, "%s /n", commandline);//.........这里部分代码省略.........
开发者ID:Lizzy0Sun,项目名称:DHSVM_RBM,代码行数:101,


示例11: auth

static intauth (void) {    lfm_update_auth ();    if (lfm_sess[0]) {        return 0;    }    if (!lfm_user[0] || !lfm_pass[0]) {        return -1;    }    char req[4096];    time_t timestamp = time(NULL);    uint8_t sig[16];    char passmd5[33];    char token[100];    deadbeef->md5 (sig, lfm_pass, strlen (lfm_pass));    deadbeef->md5_to_str (passmd5, sig);    snprintf (token, sizeof (token), "%s%d", passmd5, (int)timestamp);    deadbeef->md5 (sig, token, strlen (token));    deadbeef->md5_to_str (token, sig);    deadbeef->conf_lock ();    const char *scrobbler_url = deadbeef->conf_get_str_fast ("lastfm.scrobbler_url", SCROBBLER_URL_LFM);#if LFM_TESTMODE    snprintf (req, sizeof (req), "%s/?hs=true&p=1.2.1&c=tst&v=1.0&u=%s&t=%d&a=%s", scrobbler_url, lfm_user, (int)timestamp, token);#else    snprintf (req, sizeof (req), "%s/?hs=true&p=1.2.1&c=%s&v=%d.%d&u=%s&t=%d&a=%s", scrobbler_url, LFM_CLIENTID, plugin.plugin.version_major, plugin.plugin.version_minor, lfm_user, (int)timestamp, token);#endif    deadbeef->conf_unlock ();    // handshake    int status = curl_req_send (req, NULL);    if (!status) {        // check status and extract session id, nowplaying url, submission url        if (strncmp (lfm_reply, "OK", 2)) {            uint8_t *p = lfm_reply;            while (*p && *p >= 0x20) {                p++;            }            *p = 0;            trace ("scrobbler auth failed, response: %s/n", lfm_reply);            goto fail;        }        uint8_t *p = lfm_reply + 2;        // skip whitespace        while (*p && *p < 0x20) {            p++;        }        // get session        if (!*p) {            trace ("unrecognized scrobbler reply:/n%s/n", lfm_reply);            goto fail;        }        uint8_t *end = p+1;        while (*end && *end >= 0x20) {            end++;        }        if (end-p > 32) {            trace ("scrobbler session id is invalid length. probably plugin needs fixing./n");            goto fail;        }        strncpy (lfm_sess, p, 32);        lfm_sess[32] = 0;        trace ("obtained scrobbler session: %s/n", lfm_sess);        p = end;        // skip whitespace        while (*p && *p < 0x20) {            p++;        }        // get nowplaying url        if (!*p) {            trace ("unrecognized scrobbler reply:/n%s/n", lfm_reply);            goto fail;        }        end = p+1;        while (*end && *end >= 0x20) {            end++;        }        if (end - p > sizeof (lfm_nowplaying_url)-1) {            trace ("scrobbler nowplaying url is too long %d:/n", (int)(end-p));            goto fail;        }        strncpy (lfm_nowplaying_url, p, end-p);        lfm_nowplaying_url[end-p] = 0;        trace ("obtained scrobbler nowplaying url: %s/n", lfm_nowplaying_url);        p = end;        // skip whitespace        while (*p && *p < 0x20) {            p++;        }        // get submission url        if (!*p) {            trace ("unrecognized scrobbler reply:/n%s/n", lfm_reply);            goto fail;        }        end = p+1;        while (*end && *end >= 0x20) {            end++;        }        if (end - p > sizeof (lfm_submission_url)-1) {            trace ("scrobbler submission url is too long: %d/n", (int)(end-p));            goto fail;//.........这里部分代码省略.........
开发者ID:popoffka,项目名称:deadbeef,代码行数:101,


示例12: go

void go(SGLVData *data, int nbiter){	int i;	mpz_t  k_rd, ZZ, tmp;	mpz_inits (k_rd, ZZ, tmp, NULL);		gmp_randstate_t rand_gen;	unsigned long seed = time(NULL); 	gmp_randinit_default(rand_gen);	gmp_randseed_ui(rand_gen, seed);			SGLVScalar k;	JacPoint jp;		struct timespec start1,start2;    struct timespec end1,end2;    uint64_t diff1,diff2, diff3;			printf("/nSGLV 256 bits benchmark, running.../n/n");			diff1 = 0;	diff2 = 0;		init_jacPoint(&jp);				for (i = 0; i < nbiter; i++) {				mpz_urandomb (k_rd, rand_gen, BIT_SIZE);		mpz_mod (k_rd, k_rd,  data->efp);						apply_endo(((data->PP)+1), (data->PP), beta); /* Point PHI_P */		add_aff_aff(((data->PP)+1), (data->PP));      /* Point P+PHI_P */						clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start1);				init_glvScalar(&k);		build_glvScalar(&k, k_rd, data->aa, data->bb, data->Na);				clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end1);		diff1 += BILLION * (end1.tv_sec - start1.tv_sec) + end1.tv_nsec - start1.tv_nsec; 				clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start1);				point_from_SGLVScalar(&jp, &k, data->PP);				clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end1);		diff2 += BILLION * (end1.tv_sec - start1.tv_sec) + end1.tv_nsec - start1.tv_nsec; 				mpz_invert (ZZ, jp.Z, p);		mpz_mul (tmp, ZZ, ZZ); // tmp = ZZ^2		//~ P is transformed in affine coordinates for next iteration		mpz_mul (data->PP[0].X, jp.X, tmp);		mpz_mod (data->PP[0].X, data->PP[0].X, p);				mpz_mul (data->PP[0].Y, jp.Y, tmp);		mpz_mul (data->PP[0].Y, data->PP[0].Y, ZZ);		mpz_mod (data->PP[0].Y, data->PP[0].Y, p);	}	diff3 = diff1 + diff2;			if (is_on_curve_jac(&jp, ca, cb)){ 		printf("/nMULT: kP OK/n");		print_jacPoint(&jp);		printf("Elapsed time = %llu %llu %llu nanoseconds/n", (long long unsigned int) diff1, (long long unsigned int) diff2, (long long unsigned int) diff3);	}	else		printf("MULT: kP non OK/n");			mpz_clears (k_rd, ZZ, tmp, NULL);	free_jacPoint(&jp);	gmp_randclear(rand_gen);}
开发者ID:eacElliptic,项目名称:Scalar-multiplications,代码行数:80,


示例13: do_source_file

/** * Does a source file. * * @param filename_in  the file to read * @param filename_out NULL (stdout) or the file to write * @param parsed_file  NULL or the filename for the parsed debug info * @param no_backup    don't create a backup, if filename_out == filename_in * @param keep_mtime   don't change the mtime (dangerous) */static void do_source_file(const char *filename_in,                           const char *filename_out,                           const char *parsed_file,                           bool       no_backup,                           bool       keep_mtime){   FILE     *pfout;   bool     did_open    = false;   bool     need_backup = false;   file_mem fm;   string   filename_tmp;   /* Do some simple language detection based on the filename extension */   if (!cpd.lang_forced || (cpd.lang_flags == 0))   {      cpd.lang_flags = language_from_filename(filename_in);   }   /* Try to read in the source file */   if (load_mem_file(filename_in, fm) < 0)   {      LOG_FMT(LERR, "Failed to load (%s)/n", filename_in);      cpd.error_count++;      return;   }   LOG_FMT(LSYS, "Parsing: %s as language %s/n",           filename_in, language_to_string(cpd.lang_flags));   if (filename_out == NULL)   {      pfout = stdout;   }   else   {      /* If the out file is the same as the in file, then use a temp file */      filename_tmp = filename_out;      if (strcmp(filename_in, filename_out) == 0)      {         /* Create 'outfile.uncrustify' */         filename_tmp = fix_filename(filename_out);         if (!no_backup)         {            if (backup_copy_file(filename_in, fm.raw) != SUCCESS)            {               LOG_FMT(LERR, "%s: Failed to create backup file for %s/n",                       __func__, filename_in);               cpd.error_count++;               return;            }            need_backup = true;         }      }      make_folders(filename_tmp);      pfout = fopen(filename_tmp.c_str(), "wb");      if (pfout == NULL)      {         LOG_FMT(LERR, "%s: Unable to create %s: %s (%d)/n",                 __func__, filename_tmp.c_str(), strerror(errno), errno);         cpd.error_count++;         return;      }      did_open = true;      //LOG_FMT(LSYS, "Output file %s/n", filename_out);   }   cpd.filename = filename_in;   uncrustify_file(fm, pfout, parsed_file);   if (did_open)   {      fclose(pfout);      if (need_backup)      {         backup_create_md5_file(filename_in);      }      if (filename_tmp != filename_out)      {         /* We need to compare and then do a rename */         if (file_content_matches(filename_tmp, filename_out))         {            /* No change - remove tmp file */            (void)unlink(filename_tmp.c_str());         }         else         {#ifdef WIN32//.........这里部分代码省略.........
开发者ID:EchoLiao,项目名称:uncrustify,代码行数:101,


示例14: main_program

intmain_program(int num_messages, int num_channels, int num_connections, const char *server_hostname, int server_port, int timeout){    struct sockaddr_in server_address;    int main_sd = -1, num_events = 0, i, event_mask, channels_per_connection, num, start_time = 0, iters_to_next_summary = 0;    Connection *connections = NULL, *connection;    Statistics stats = {0,0,0,0,0};    int exitcode = EXIT_SUCCESS;    struct epoll_event events[MAX_EVENTS];    char buffer[BIG_BUFFER_SIZE];    info("Publisher starting up/n");    info("Publish: %d messages to %d channels on server: %s:%d/n", num_messages, num_channels, server_hostname, server_port);    if ((fill_server_address(server_hostname, server_port, &server_address)) != 0) {        error2("ERROR host name not found/n");    }    if ((main_sd = epoll_create(200 /* this size is not used on Linux kernel 2.6.8+ */)) < 0) {        error3("Failed %d creating main epoll socket/n", errno);    }    if ((connections = init_connections(num_connections, &server_address, main_sd)) == NULL) {        error2("Failed to create to connections/n");    }    stats.requested_connections = num_connections;    channels_per_connection = num_channels / num_connections;    for (i = 0; i < num_connections; i++) {        num = i * channels_per_connection;        connections[i].channel_start = num;        num += channels_per_connection - 1;        connections[i].channel_end = ((num > num_channels) || (i == (num_connections - 1))) ? num_channels - 1 : num;    }    // infinite loop    debug("Entering Infinite Loop/n");    iters_to_next_summary = ITERATIONS_TILL_SUMMARY_PER_TIMEOUT/timeout;    for(;;) {        if ((num_events = epoll_wait(main_sd, events, MAX_EVENTS, timeout)) < 0) {            error3("epoll_wait failed/n");        }        for (i = 0; i < num_events; i++) {            event_mask = events[i].events;            connection = (Connection *)(events[i].data.ptr);            if ((connection->message_count >= num_messages) && (connection->channel_id > connection->channel_end)) {                // remove write flag from event                if (change_connection(connection, EPOLLIN | EPOLLHUP) < 0) {                    error2("Failed creating socket for connection = %d/n", connection->index);                }                if (event_mask & EPOLLOUT) { // WRITE                    continue;                }            }            if (event_mask & EPOLLHUP) { // SERVER HUNG UP                debug("EPOLLHUP/n");                info("Server hung up on conncetion %d. Reconecting.../n", connection->index);                sleep(1);                reopen_connection(connection);                continue;            }            if (event_mask & EPOLLERR) {                debug("EPOLLERR/n");                info("Server returned an error on connection %d. Reconecting.../n", connection->index);                reopen_connection(connection);                continue;            }            if (event_mask & EPOLLIN) { // READ                debug("----------READ AVAILABLE-------/n");                if (connection->state == CONNECTED) {                    read_response(connection, &stats, buffer, BIG_BUFFER_SIZE);                }            }            if (event_mask & EPOLLOUT) { // WRITE                debug("----------WRITE AVAILABLE-------/n");                if (start_time == 0) {                    start_time = time(NULL);                }                if (connection->state == CONNECTING) {                    connection->state = CONNECTED;                    stats.connections++;                    debug("Connection opened for index=%d/n", connection->index);                }                write_message(connection, &stats);//.........这里部分代码省略.........
开发者ID:midnightskinhead,项目名称:nginx-push-stream-module,代码行数:101,


示例15: feedAppendOnlyFile

static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {    sds buf = sdsempty();    int j;    ssize_t nwritten;    time_t now;    robj *tmpargv[3];    /* The DB this command was targetting is not the same as the last command     * we appendend. To issue a SELECT command is needed. */    if (dictid != server.appendseldb) {        char seldb[64];        snprintf(seldb,sizeof(seldb),"%d",dictid);        buf = sdscatprintf(buf,"*2/r/n$6/r/nSELECT/r/n$%lu/r/n%s/r/n",            (unsigned long)strlen(seldb), seldb);        server.appendseldb = dictid;    }    /* "Fix" the argv vector if the command is EXPIRE. We want to translate     * EXPIREs into EXPIREATs calls */    if (cmd->proc == expireCommand) {        long when;        tmpargv[0] = createStringObject("EXPIREAT",8);        tmpargv[1] = argv[1];        incrRefCount(argv[1]);        when = time(NULL)+strtol(argv[2]->ptr,NULL,10);        tmpargv[2] = createObject(REDIS_STRING,            sdscatprintf(sdsempty(),"%ld",when));        argv = tmpargv;    }    /* Append the actual command */    buf = sdscatprintf(buf,"*%d/r/n",argc);    for (j = 0; j < argc; j++) {        robj *o = argv[j];        o = getDecodedObject(o);        buf = sdscatprintf(buf,"$%lu/r/n",(unsigned long)sdslen(o->ptr));        buf = sdscatlen(buf,o->ptr,sdslen(o->ptr));        buf = sdscatlen(buf,"/r/n",2);        decrRefCount(o);    }    /* Free the objects from the modified argv for EXPIREAT */    if (cmd->proc == expireCommand) {        for (j = 0; j < 3; j++)            decrRefCount(argv[j]);    }    /* We want to perform a single write. This should be guaranteed atomic     * at least if the filesystem we are writing is a real physical one.     * While this will save us against the server being killed I don't think     * there is much to do about the whole server stopping for power problems     * or alike */     nwritten = write(server.appendfd,buf,sdslen(buf));    /* If a background append only file rewriting is in progress we want to     * accumulate the differences between the child DB and the current one     * in a buffer, so that when the child process will do its work we     * can append the differences to the new append only file. */    if (server.bgrewritechildpid != -1)        server.bgrewritebuf = sdscatlen(server.bgrewritebuf,buf,sdslen(buf));    sdsfree(buf);    now = time(NULL);    if (server.appendfsync == APPENDFSYNC_ALWAYS ||        (server.appendfsync == APPENDFSYNC_EVERYSEC &&         now-server.lastfsync > 1))    {        fsync(server.appendfd); /* Let's try to get this data on the disk */        server.lastfsync = now;    }}
开发者ID:N3xtHub,项目名称:redis-1.3.7,代码行数:74,


示例16: perform_http

void perform_http(char *request, char *response, char *directory){	/* variable declaration: */	char http_code[4]; // holds the http code as a char array	FILE *fp; // file pointer for the requested file	char status[100]; // status of the http code	char method[20]; // the method in the http request	char location[200]; // the location of the file requested	char temp_directory[MAX_STR_LEN] = {0}; //to hold the full directory of the desired file	char http_version[10]; // the version of http being used	char *token; // a pointer to tokenize the request	char time_str[100]; // a char array to hold the current time in a specific format	char *file_buf; // a char array to hold the contents of the requested file	time_t cur_time; // gets and holds the current time		/* tokenize the request to get "method", "location" and "http_version" */	token = strtok(request, " ");	strncpy(method, token, 20);		token = strtok(NULL, " ");	strncpy(location, token, 200);		token = strtok(NULL, " ");	strncpy(http_version, strtok(token, "/r"), 10);		/* the location parsed is actually the full uri sent by the client,	*  must get the actual location of the requested file from the end of the uri	*/	token = strtok(location, "/");	// check if the first part of the uri is "http:" 	if(strncmp(token, "http:", 5)==0){		token = strtok(NULL, "/");	}	// get the next part of the uri (hostname)	token = strtok(NULL, "/0");	/* append a forward slash to "temp_directory"	*  and then append the location of the requested file */	strncpy(temp_directory, directory, strlen(directory));	strncat(temp_directory, "/", 2);	strncat(temp_directory, token, 200);		//attempt to topen the requested file in the specified location	fp = fopen(temp_directory, "r");	// if the porgram fails to open the file, assing http code "404"	if(fp == NULL)	{		strncpy(http_code, "404", 4);		strncpy(status, "File not found", 15);	}else	{//otherwise assign code "200"		strncpy(http_code, "200", 4);		strncpy(status, "OK", 3);	}	if(strncmp(method, "GET", 4) != 0)	{//check if the method in the request is implemented in this program		// if it is not, assign http code "501"		strncpy(http_code, "501", 4);		strncpy(status, "Not implemented", 16);		fp = NULL;	}		// if the file was successfully opened, read it	if(fp != NULL)	{		if((file_buf = read_file(fp, file_buf)) == NULL)		{			// if the file is unreadable, assign http code 404			strncpy(http_code, "404", 4);			strncpy(status, "File not found", 15);		}		// close the file after reading		fclose(fp);	}		// get the current time	cur_time = time(0);	// format it for ease of reading	strftime(time_str, 100, "%a %d, %b %Y %T PST", localtime(&cur_time));		/* start to construct the response with 	*  information about the request,	*  the date, and the server being used	*/	strncat(response, "---Response Header---/n", 22);	strncat(response, http_version, strlen(http_version));	strncat(response, " ", 2);	strncat(response, http_code, 4);	strncat(response, " ", 2);	strncat(response, status, strlen(status));	strncat(response, "/nDate: ", 8);	strncat(response, time_str, strlen(time_str));	strncat(response, "/nServer: Apache/2.2.31 (Unix) mod_jk/1.2.40/n/n", 45);		// if the file was successfully read, concatenate it to the response	strncat(response, "---Response Body---/n", 21);	if(fp != NULL)	{		strncat(response, file_buf, strlen(file_buf));	}	//.........这里部分代码省略.........
开发者ID:AlanMackay,项目名称:HTTPServer,代码行数:101,


示例17: initialization

/* Initialization of neurons parameters */int initialization(neuron **nrn, int numNeurons, int simTime){    int i, j, idj, size=0;    char *fname;    double tmp;    FILE *fp, *fq;    srand (time(NULL));            for(i = 0; i < numNeurons; ++i){        (*nrn)[i].numPreSyn = 0;        (*nrn)[i].E = 0.0;        for(j = 0; j < simTime; ++j){            (*nrn)[i].V[j] = randm(0.01, 0.1);            (*nrn)[i].Z[j] = randm(0.01, 0.05);            (*nrn)[i].S[j] = randm(0.01, 0.05);            (*nrn)[i].N[j] = randm(0.01, 0.05);        }    }    if(!(fp = fopen("stimuli.dat", "r"))){        fname = "stimuli.dat";        goto fail;    }    for(i = 0; i < numNeurons; ++i){        for(j = 0; j < simTime; ++j){            fscanf(fp, "%lf", &(*nrn)[i].Iext[j]);        }    }        fclose(fp);    if(!(fq = fopen("synapses.dat", "r"))){        fname = "synapses.dat";        goto fail;    }    for(i = 0; i < numNeurons; ++i){        idj = 0;        for(j = 0; j < numNeurons; ++j){            fscanf(fp, "%lf", &tmp);            if (tmp != 0){                if (j == 0){                    (*nrn)[i].W[0] = tmp;                    (*nrn)[i].pre_id[0] = j;                }else{                    size++;                    (*nrn)[i].W = (double *)realloc((*nrn)[i].W, size*sizeof(double));                    (*nrn)[i].W[idj] = tmp;                    (*nrn)[i].pre_id = (int *)realloc((*nrn)[i].pre_id,                                size*sizeof(int));                    (*nrn)[i].pre_id[idj] = j;                    idj++;                }                (*nrn)[i].numPreSyn++;            }        }    }    fclose(fp);    return 0;fail:    printf("File %s cannot be opened!/n", fname);    exit(-1);}
开发者ID:gdetor,项目名称:Crebral,代码行数:70,


示例18: main

int main( int argc, char** argv ){	unsigned int tickDelta;	unsigned int currTicks;	unsigned int physicsTickAcc;	int numPhysicsProcesses;	float renderDelta;#ifdef _DEBUG	SDL_LogSetAllPriority( SDL_LOG_PRIORITY_VERBOSE );#else	SDL_LogSetAllPriority( SDL_LOG_PRIORITY_WARN );#endif	SDL_LogSetAllPriority( SDL_LOG_PRIORITY_VERBOSE );	if( initEverything( ) < 0 ) {		return 1;	}	srand( (unsigned int)time( NULL ) );	/* main loop */	running = 1;	lastTicks = SDL_GetTicks( );	physicsTickAcc = 0;	gsmEnterState( &globalFSM, &titleScreenState );	while( running ) {		if( !focused ) {			processEvents( 1 );			continue;		}		currTicks = SDL_GetTicks( );		tickDelta = currTicks - lastTicks;		lastTicks = currTicks;		physicsTickAcc += tickDelta;		/* process input */		processEvents( 0 );		sys_Process( );		gsmProcess( &globalFSM );		/* process movement and collision */		numPhysicsProcesses = 0;		while( physicsTickAcc > PHYSICS_TICK ) {			sys_PhysicsTick( PHYSICS_DELTA );			gsmPhysicsTick( &globalFSM, PHYSICS_DELTA );			physicsTickAcc -= PHYSICS_TICK;			++numPhysicsProcesses;		}		/* rendering */		if( numPhysicsProcesses > 0 ) {			/* set the new render positions */			renderDelta = PHYSICS_DELTA * (float)numPhysicsProcesses;			gfx_ClearDrawCommands( renderDelta );			cam_FinalizeStates( renderDelta );			/* render all the things */			sys_Draw( );			gsmDraw( &globalFSM );		}		float dt = (float)tickDelta / 1000.0f;		cam_Update( dt );		gfx_Render( dt );		// flip here so we don't have to store the window anywhere else		SDL_GL_SwapWindow( window );	}	return 0;}
开发者ID:JesseRahikainen,项目名称:LD33_Oszmot,代码行数:77,


示例19: yahoo_io_thread

int32yahoo_io_thread( void * _data ){	YahooConnection * conn = (YahooConnection*)_data;	/*	conn->fID = yahoo_init_with_attributes(		conn->fYahooID, conn->fPassword,		//"local_host", local_host,		"pager_port", 23,		NULL	);*/		conn->fID = yahoo_init(		conn->fYahooID, conn->fPassword	);		LOG(kProtocolName, liDebug, "yahoo_io_thread: id: %s, pass: %s", conn->fYahooID, conn->fPassword );		gYahooConnections[conn->fID] = conn;		yahoo_login( conn->fID, YAHOO_STATUS_AVAILABLE );	int lfd=0;		fd_set inp, outp;	struct timeval tv;		LOG(kProtocolName, liDebug, "yahoo_io_thread: Starting loop");		while( conn->IsAlive() ) {		FD_ZERO(&inp);		FD_ZERO(&outp);		tv.tv_sec=1;		tv.tv_usec=0;		lfd=0;				for(int i=0; i<conn->CountConnections(); i++) {			struct fd_conn *c = conn->ConnectionAt(i);						if(c->remove) {//				LOG(kProtocolName, liDebug, "yahoo_io_thread: Removing id:%d fd:%d", c->id, c->fd);				conn->RemoveConnection(c);				free(c);			} else {				if(c->cond & YAHOO_INPUT_READ) {					FD_SET(c->fd, &inp);				}				if(c->cond & YAHOO_INPUT_WRITE) {					FD_SET(c->fd, &outp);				}				if(lfd < c->fd)					lfd = c->fd;			}		}				select(lfd + 1, &inp, &outp, NULL, &tv);		time(&curTime);				for(int i=0; i<conn->CountConnections(); i++) {			struct fd_conn *c = conn->ConnectionAt(i);			if(c->remove)				continue;			if(FD_ISSET(c->fd, &inp)) {//				LOG(kProtocolName, liDebug, "yahoo_io_thread: data to read");				yahoo_callback(c, YAHOO_INPUT_READ);				FD_CLR(c->fd, &inp);			}			if(FD_ISSET(c->fd, &outp)) {				//LOG(kProtocolName, liDebug, "yahoo_io_thread: data to write");				yahoo_callback(c, YAHOO_INPUT_WRITE);				FD_CLR(c->fd, &outp);			}		}				if(expired(pingTimer))			yahoo_ping_timeout_callback(conn->fID, pingTimer);	}	LOG(kProtocolName, liDebug, "yahoo_io_thread: Exited loop");		while( conn->CountConnections() > 0 ) {		struct fd_conn * c = conn->ConnectionAt(0);		conn->RemoveConnection(c);		close(c->fd);		FREE(c);	}		return 0;}
开发者ID:louisdem,项目名称:IMKit,代码行数:88,


示例20: Packet

		Packet(Ip::Endpoint e, udp::Header h): header(h), parts(h.totalParts), created(time(0)), validParts(0), endpoint(e) {}
开发者ID:Mogito89,项目名称:TOX002,代码行数:1,


示例21: repeate_cb

static void repeate_cb (EV_P_ ev_timer *w, int revents){    printf("repeate at %ju/n", (uintmax_t)time(NULL));}
开发者ID:jasonblog,项目名称:note,代码行数:4,


示例22: GetRandomSound

void TinMan::Run(){	FMOD::Sound * primarySound = GetRandomSound();	FMOD::Channel * primaryChannel;	result = system->playSound(FMOD_CHANNEL_FREE, primarySound, true, &primaryChannel);	ERRCHECK();	primaryChannel->setVolume(0.f);	primaryChannel->setPaused(false);	FMOD::Sound * secondarySound = 0;	FMOD::Channel * secondaryChannel = 0;	const unsigned int crossfadeTime = 2500;	time_t voiceStartTime = time(0) + 10 + (rand() % 20);	while(true)	{		system->update();		bool isPlaying = false;		result = primaryChannel->isPlaying(&isPlaying);		if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))		{				ERRCHECK();		}		if(isPlaying)		{			unsigned int primaryPos = 0;			unsigned int primaryLen = 0;			result = primaryChannel->getPosition(&primaryPos, FMOD_TIMEUNIT_MS);			if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))			{					ERRCHECK();			}			result = primarySound->getLength(&primaryLen, FMOD_TIMEUNIT_MS);			ERRCHECK();			float volume = 1.f;			if(primaryPos < crossfadeTime)			{				volume = std::max(0.f, std::min((float)(primaryPos)/(float)crossfadeTime, 1.f));			}			else if(primaryPos > primaryLen - crossfadeTime)			{				volume = std::max(0.f, std::min((float)(primaryLen - primaryPos)/(float)crossfadeTime, 1.f));			}			//std::cout<<std::time(0)<<" "<<voiceStartTime<<" "<<primaryPos<<"/"<<primaryLen<<" "<<volume<<"/n";			result = primaryChannel->setVolume(volume);			if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))			{					ERRCHECK();			}			if(primaryPos > primaryLen - crossfadeTime)			{				if(!secondaryChannel)				{					secondarySound = GetRandomSound();					result = system->playSound(FMOD_CHANNEL_FREE, secondarySound, true, &secondaryChannel);					ERRCHECK();					result = secondaryChannel->setVolume(1.f - volume);					ERRCHECK();					result = secondaryChannel->setPaused(false);					ERRCHECK();				}				else				{					secondaryChannel->setVolume(1.f - volume);					if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))					{							ERRCHECK();					}				}			}		}		else		{			if(secondaryChannel && secondarySound)			{				primaryChannel = secondaryChannel;				primarySound = secondarySound;				secondaryChannel = 0;			}			else			{				// for some reason all channels are stopped				primarySound = GetRandomSound();				result = system->playSound(FMOD_CHANNEL_FREE, primarySound, 0, &primaryChannel);				ERRCHECK();			}		}		if(time(0) >= voiceStartTime)		{//.........这里部分代码省略.........
开发者ID:ghisguth,项目名称:tinman,代码行数:101,


示例23: rm_test_0

void rm_test_0(ull r, ull m, int k, int max_iter, FILE *fout) {	ull wordsize = 0, dim = 0, gen_size = 0;	unsigned char *G = NULL, *D = NULL, *DD = NULL, *C = NULL, *NC = NULL;	unsigned short *masks = NULL, width = 0;	ull accumulator = 0, n = 0;	ull data_block_size_bytes = 0;	ull code_block_size_bytes = 0;	dim = rm_dim(r, m);	wordsize = rm_wordsize(r, m);	width = rm_codeword_size_in_bytes(r, m);	gen_size = gen_matrix_mem_size(m, m);	G = (unsigned char *) malloc(gen_size);	generate_matrix(m, m, G);		//print(dim, 8 * width, G);printf("/n");	masks = (unsigned short *) malloc(wordsize * sizeof(unsigned short));	generate_masks(m, masks);	data_block_size_bytes = rm_dataword_size_in_bytes(r, m);	code_block_size_bytes = rm_codeword_size_in_bytes(r, m);	D =	(unsigned char *) malloc(data_block_size_bytes);	DD = (unsigned char *) malloc(data_block_size_bytes);	for (int i = 0; i < data_block_size_bytes; ++i)		D[i] = (unsigned char) rand();	C = (unsigned char *) malloc(code_block_size_bytes);	NC = (unsigned char *) malloc(code_block_size_bytes);	encode_block(r, m, dim, wordsize, C, D, masks, G);	//printf("Data:/n");print(1, dim, D);printf("/n");		memcpy(NC, C, width);	// print(1, wordsize, C);printf("/n");	// decode_block(r, m, dim, wordsize, NC, DD, masks, G, width);	// print(1, dim, DD);	srand (time(NULL));		n = 2 * k / 3 + 1;	fprintf(fout, "%lld/n", n);	for (ull i = 0; i < n; i++) {		accumulator = 0;		fprintf(fout, "%1.9lf ", (double) i / (double) k);		for (ull j = 0; j < max_iter; ++j) {			memcpy(NC, C, code_block_size_bytes);				add_noise(NC, code_block_size_bytes, (double) i / (double) k);							decode_block(r, m, dim, wordsize, NC, DD, masks, G, width);			accumulator += match(data_block_size_bytes, 0, dim, D, DD);		}		fprintf(fout, "%1.9lf/n", (double) accumulator / (double) max_iter);	}	FREE_IF_ALLOCATED(C);	FREE_IF_ALLOCATED(NC);	FREE_IF_ALLOCATED(D);	FREE_IF_ALLOCATED(DD);	FREE_IF_ALLOCATED(masks);	FREE_IF_ALLOCATED(G);}
开发者ID:sergeykhegay,项目名称:university_projects,代码行数:66,


示例24: main

int main(int argc, char *argv[]){    if(argc < 2)    {        cerr << "usage: dcpu <flags> <filename>/n";        return 1;    }    bool debug = false;    int time_to_kill_ms = 0;    // -d runs in debug mode, prints out memory dump at end    for(int a = 1; a < argc - 1; a++)    {        if(!strcmp(argv[a], "-d"))        {            debug = true;        }else        {            cerr << "invalid command <" << argv[a] << ">. ignoring/n";        }    }    ifstream inFile(argv[argc - 1], ios::in);    if(!inFile.good())    {        cerr << "Could not open <" << argv[argc - 1] << ">/n";        return 1;    }    Dcpu cpu(inFile, debug);    sf::Thread cpu_thread(&start, &cpu);    sf::RenderWindow app(sf::VideoMode(TERMINAL_WIDTH * 4 * 4, TERMINAL_HEIGHT * 8 * 4), "DCPPU: DCPU-16 Emulator");    app.SetFramerateLimit(30); // Getting 1500 fps on somthing this simple seems wasteful    sf::Image font;    if(!font.LoadFromFile("font.png"))    {        cerr << "Could not load font/n";        return 1;    }    unsigned short *buf = cpu.GetScreenBuffer();    buf += TERMINAL_WIDTH * TERMINAL_HEIGHT;    // load and encode character set into RAM    for(int char_off = 0; char_off < 128; char_off++)    {        int font_off_x = (char_off * 4) % 128;        int font_off_y = ((char_off * 4) / 128) * 8;        unsigned int font_char = 0;        int x_ = 0;        int y_ = 0;        for(int x = font_off_x; x < font_off_x + 4; x++)        {            for(int y = font_off_y; y < font_off_y + 8; y++)            {                sf::Color pix = font.GetPixel(x, y);                 if(pix != sf::Color(2, 1, 2))                    font_char |= 1 << (31-((y_ * 4) + x_));                y_++;            }            x_++;        }        unsigned short lowerword = font_char & 0xffff;        unsigned short upperword = (font_char >> 16) & 0xffff;        buf[char_off * 2] = upperword;        buf[char_off * 2 + 1] = lowerword;    }    sf::Image screen;    screen.Create(128, 96); // create black image    screen.SetSmooth(false);    sf::Sprite screen_sprite(screen);    screen_sprite.SetScale(4.0, 4.0);    cpu_thread.Launch();    bool running = true;    while(running)    {        sf::Event Event;        while(app.GetEvent(Event))        {            if(Event.Type == sf::Event::Closed)            {                cpu.kill();                running = false;                app.Close();            }            if (Event.Type == sf::Event::TextEntered)            {                if (Event.Text.Unicode < 128)                {//.........这里部分代码省略.........
开发者ID:ryban,项目名称:DCPPU16,代码行数:101,


示例25: srand

/*	* autoPlay()	*	* Simulates a game of Red Rover and notifies the user of the winning team.	*	* Selects a random player from one team to attempt to break through a random player from the other team until one team has won.	*	* Starting with Team A, teams take turns attempting to break through.	*	* When the function ends, both teams should be emptied.	*	* this function returns nothing, but it MUST print out	* 		the name of the runner	* 		the name of the defender and	* 		the players on each team	* after each attempt to break through.	*	* At the end of the game, print out the name of the winning team and the players on both teams.	*/void RedRover::autoPlay(){    srand(time(0));    int rand_index_runner = 0, rand_index_defender = 0, i = 0;        PlayerInterface* runner = NULL;    PlayerInterface* defender = NULL;        bool playing = true;    if (roster.size() < 4)    {        cout << "INSUFFICIENT PLAYERS/n/n";        return;    }        createTeams();        //cout << "TEAM A: " << getTeamA() << endl;    //cout << "TEAM B: " << getTeamB() << endl << endl;        while (playing)    {        if (i % 2 == 0)        {   //cout << "I: " << i << "rand: " << rand() % 6 << endl;            //team a turn            rand_index_runner = rand() % getTeamASize(); // grab random player from A as runner            runner = teamA.at(rand_index_runner);                        rand_index_defender = rand() % getTeamBSize(); // grab random player from B As Defender            defender = teamB.at(rand_index_defender);                    }        else if (i % 2 == 1)        {            //team b turn            rand_index_runner = rand() % getTeamBSize(); // grab random player from B as runner            runner = teamB.at(rand_index_runner);                        rand_index_defender = rand() % getTeamASize(); // grab random player from A As Defender            defender = teamA.at(rand_index_defender);        }                cout << "RUNNER: " << runner->getName() << endl;        cout << "DEFENDER: " << defender->getName() << endl << endl;                sendSomeoneOver(runner, defender);                if (teamA.size() > 1 && teamB.size() > 1)        {            cout << "TEAM A: " << getTeamA() << endl;            cout << "TEAM B: " << getTeamB() << endl << endl;        }        else if (teamA.size() == 1 || teamB.size() == 1)        {            if (teamA.size() == 1)            {                cout << "Team A lost! " << getTeamA() << endl << endl;            }            else if (teamB.size() == 1)            {                cout << "Team B lost! " << getTeamB() << endl << endl;            }            playing = false;        }        i++;    }        teamReset();}
开发者ID:tebbsja,项目名称:cs235,代码行数:90,


示例26: xptClient_processPacket_blockData1

/* * Called when a packet with the opcode XPT_OPC_S_WORKDATA1 is received * This is the first version of xpt 'getwork' */bool xptClient_processPacket_blockData1(xptClient_t* xptClient){	// parse block data	bool recvError = false;	xptPacketbuffer_beginReadPacket(xptClient->recvBuffer);	// update work info, GBT style (sha256 & scrypt)	xptClient->blockWorkInfo.version = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);				// version	xptClient->blockWorkInfo.height = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);				// block height	xptClient->blockWorkInfo.nBits = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);				// nBits	// New in xpt version 6 - Targets are send in compact format (4 bytes instead of 32)	uint32 targetCompact = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);	uint32 targetShareCompact = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);	xptClient_getDifficultyTargetFromCompact(targetCompact, (uint32*)xptClient->blockWorkInfo.target);	xptClient_getDifficultyTargetFromCompact(targetShareCompact, (uint32*)xptClient->blockWorkInfo.targetShare);	xptClient->blockWorkInfo.nTime = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);				// nTimestamp	xptPacketbuffer_readData(xptClient->recvBuffer, xptClient->blockWorkInfo.prevBlockHash, 32, &recvError);	// prevBlockHash	xptPacketbuffer_readData(xptClient->recvBuffer, xptClient->blockWorkInfo.merkleRoot, 32, &recvError);		// merkleroot	// coinbase part1 (16bit length + data)	xptClient->blockWorkInfo.coinBase1Size = xptPacketbuffer_readU16(xptClient->recvBuffer, &recvError);	xptPacketbuffer_readData(xptClient->recvBuffer, xptClient->blockWorkInfo.coinBase1, xptClient->blockWorkInfo.coinBase1Size, &recvError);	// coinbase part2 (16bit length + data)	xptClient->blockWorkInfo.coinBase2Size = xptPacketbuffer_readU16(xptClient->recvBuffer, &recvError);	xptPacketbuffer_readData(xptClient->recvBuffer, xptClient->blockWorkInfo.coinBase2, xptClient->blockWorkInfo.coinBase2Size, &recvError);	// information about remaining tx hashes	xptClient->blockWorkInfo.txHashCount = xptPacketbuffer_readU16(xptClient->recvBuffer, &recvError);	printf("New block data - height: %d tx count: %d/n", xptClient->blockWorkInfo.height, xptClient->blockWorkInfo.txHashCount);	for(uint32 i=0; i<xptClient->blockWorkInfo.txHashCount; i++)	{		xptPacketbuffer_readData(xptClient->recvBuffer, xptClient->blockWorkInfo.txHashes+(32*i), 32, &recvError);		// The first hash in xptClient->blockWorkInfo.txHashes is reserved for the coinbase transaction	}	xptClient->blockWorkInfo.timeWork = time(NULL);	xptClient->blockWorkInfo.timeBias = xptClient->blockWorkInfo.nTime - (uint32)time(NULL);	xptClient->hasWorkData = true;	// add general block info (primecoin new pow for xpt v4, removed in xpt v5)	//EnterCriticalSection(&xptClient->cs_workAccess);	//float earnedShareValue = xptPacketbuffer_readFloat(xptClient->recvBuffer, &recvError);	//xptClient->earnedShareValue += earnedShareValue;	//uint32 numWorkBundle = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError); // how many workBundle blocks we have	//for(uint32 b=0; b<numWorkBundle; b++)	//{	//	// general block info	//	uint32 blockVersion = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);	//	uint32 blockHeight = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);	//	uint32 blockBits = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);	//	uint32 blockBitsForShare = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);	//	uint32 blockTimestamp = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);	//	uint32 workBundleFlags = xptPacketbuffer_readU8(xptClient->recvBuffer, &recvError);	//	uint8 prevBlockHash[32];	//	xptPacketbuffer_readData(xptClient->recvBuffer, prevBlockHash, 32, &recvError);	//	// server constraints	//	uint32 fixedPrimorial = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);	//	uint32 fixedHashFactor = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);	//	uint32 sievesizeMin = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);	//	uint32 sievesizeMax = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);	//	uint32 primesToSieveMin = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);	//	uint32 primesToSieveMax = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);	//	uint32 sieveChainLength = xptPacketbuffer_readU8(xptClient->recvBuffer, &recvError);	//	uint32 nonceMin = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);	//	uint32 nonceMax = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);	//	uint32 numPayload =  xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);	//	for(uint32 p=0; p<numPayload; p++)	//	{	//		xptBlockWorkInfo_t* blockData = xptClient->blockWorkInfo + xptClient->blockWorkSize;	//		if( xptClient->blockWorkSize >= 400 )	//			break;	//		blockData->version = blockVersion;	//		blockData->height = blockHeight;	//		blockData->nBits = blockBits;	//		blockData->nBitsShare = blockBitsForShare;	//		blockData->nTime = blockTimestamp;	//		memcpy(blockData->prevBlockHash, prevBlockHash, 32);	//		blockData->flags = workBundleFlags;	//		blockData->fixedPrimorial = fixedPrimorial;	//		blockData->fixedHashFactor = fixedHashFactor;	//		blockData->sievesizeMin = sievesizeMin;	//		blockData->sievesizeMax = sievesizeMax;	//		blockData->primesToSieveMin = primesToSieveMin;	//		blockData->primesToSieveMax = primesToSieveMax;	//		blockData->sieveChainLength = sieveChainLength;	//		blockData->nonceMin = nonceMin;	//		blockData->nonceMax = nonceMax;	//		blockData->flags = workBundleFlags;	//		xptPacketbuffer_readData(xptClient->recvBuffer, blockData->merkleRoot, 32, &recvError);	//		xptClient->blockWorkSize++;	//	}	//}	//LeaveCriticalSection(&xptClient->cs_workAccess);	return true;}
开发者ID:zaknafeinx,项目名称:xptMiner,代码行数:94,


示例27: time

void CSendFileDlg::onFileStart(){		start_time = time(NULL);	}
开发者ID:cysfek,项目名称:openq-ng.linq2,代码行数:4,


示例28: rewriteAppendOnlyFile

/* Write a sequence of commands able to fully rebuild the dataset into * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */static int rewriteAppendOnlyFile(char *filename) {    dictIterator *di = NULL;    dictEntry *de;    FILE *fp;    char tmpfile[256];    int j;    time_t now = time(NULL);    /* Note that we have to use a different temp name here compared to the     * one used by rewriteAppendOnlyFileBackground() function. */    snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());    fp = fopen(tmpfile,"w");    for (j = 0; j < server.dbnum; j++) {        char selectcmd[] = "*2/r/n$6/r/nSELECT/r/n";        redisDb *db = server.db+j;        dict *d = db->dict;        if (dictSize(d) == 0) continue;        di = dictGetIterator(d);        /* SELECT the new DB */        fwrite(selectcmd,sizeof(selectcmd)-1,1,fp);        fwriteBulkLong(fp,j);        /* Iterate this DB writing every entry */        while((de = dictNext(di)) != NULL) {            robj *key, *o;            time_t expiretime;            int swapped;            key = dictGetEntryKey(de);            /* If the value for this key is swapped, load a preview in memory.             * We use a "swapped" flag to remember if we need to free the             * value object instead to just increment the ref count anyway             * in order to avoid copy-on-write of pages if we are forked() */            if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||                key->storage == REDIS_VM_SWAPPING) {                o = dictGetEntryVal(de);                swapped = 0;            } else {                o = vmPreviewObject(key);                swapped = 1;            }            expiretime = getExpire(db,key);            /* Save the key and associated value */            if (o->type == REDIS_STRING) {                /* Emit a SET command */                char cmd[]="*3/r/n$3/r/nSET/r/n";                fwrite(cmd, sizeof(cmd)-1,1,fp);                /* Key and value */                fwriteBulkObject(fp,key);                fwriteBulkObject(fp,o);            }             else if (o->type == REDIS_LIST) {                /* Emit the RPUSHes needed to rebuild the list */                list *list = o->ptr;                listNode *ln;                listIter li;                listRewind(list,&li);                while((ln = listNext(&li))) {                    char cmd[]="*3/r/n$5/r/nRPUSH/r/n";                    robj *eleobj = listNodeValue(ln);                    fwrite(cmd, sizeof(cmd)-1, 1, fp);                    fwriteBulkObject(fp,key);                    fwriteBulkObject(fp,eleobj);                }            }             else if (o->type == REDIS_SET) {                /* Emit the SADDs needed to rebuild the set */                dict *set = o->ptr;                dictIterator *di = dictGetIterator(set);                dictEntry *de;                while((de = dictNext(di)) != NULL) {                    char cmd[]="*3/r/n$4/r/nSADD/r/n";                    robj *eleobj = dictGetEntryKey(de);                    fwrite(cmd,sizeof(cmd)-1,1,fp) ;                    fwriteBulkObject(fp,key) ;                    fwriteBulkObject(fp,eleobj);                }                dictReleaseIterator(di);            }             else if (o->type == REDIS_ZSET) {                /* Emit the ZADDs needed to rebuild the sorted set */                zset *zs = o->ptr;                dictIterator *di = dictGetIterator(zs->dict);                dictEntry *de;                while((de = dictNext(di)) != NULL) {                    char cmd[]="*4/r/n$4/r/nZADD/r/n";                    robj *eleobj = dictGetEntryKey(de);                    double *score = dictGetEntryVal(de);//.........这里部分代码省略.........
开发者ID:N3xtHub,项目名称:redis-1.3.7,代码行数:101,


示例29: _try_sched

/* Attempt to schedule a specific job on specific available nodes * IN job_ptr - job to schedule * IN/OUT avail_bitmap - nodes available/selected to use * IN exc_core_bitmap - cores which can not be used * RET SLURM_SUCCESS on success, otherwise an error code */static int  _try_sched(struct job_record *job_ptr, bitstr_t **avail_bitmap,                       uint32_t min_nodes, uint32_t max_nodes,                       uint32_t req_nodes, bitstr_t *exc_core_bitmap){    bitstr_t *tmp_bitmap;    int rc = SLURM_SUCCESS;    int feat_cnt = _num_feature_count(job_ptr);    List preemptee_candidates = NULL;    List preemptee_job_list = NULL;    if (feat_cnt) {        /* Ideally schedule the job feature by feature,         * but I don't want to add that complexity here         * right now, so clear the feature counts and try         * to schedule. This will work if there is only         * one feature count. It should work fairly well         * in cases where there are multiple feature         * counts. */        struct job_details *detail_ptr = job_ptr->details;        ListIterator feat_iter;        struct feature_record *feat_ptr;        int i = 0, list_size;        uint16_t *feat_cnt_orig = NULL, high_cnt = 0;        /* Clear the feature counts */        list_size = list_count(detail_ptr->feature_list);        feat_cnt_orig = xmalloc(sizeof(uint16_t) * list_size);        feat_iter = list_iterator_create(detail_ptr->feature_list);        while ((feat_ptr =                    (struct feature_record *) list_next(feat_iter))) {            high_cnt = MAX(high_cnt, feat_ptr->count);            feat_cnt_orig[i++] = feat_ptr->count;            feat_ptr->count = 0;        }        list_iterator_destroy(feat_iter);        if ((job_req_node_filter(job_ptr, *avail_bitmap) !=                SLURM_SUCCESS) ||                (bit_set_count(*avail_bitmap) < high_cnt)) {            rc = ESLURM_NODES_BUSY;        } else {            preemptee_candidates =                slurm_find_preemptable_jobs(job_ptr);            rc = select_g_job_test(job_ptr, *avail_bitmap,                                   high_cnt, max_nodes, req_nodes,                                   SELECT_MODE_WILL_RUN,                                   preemptee_candidates,                                   &preemptee_job_list,                                   exc_core_bitmap);            if (preemptee_job_list) {                list_destroy(preemptee_job_list);                preemptee_job_list = NULL;            }        }        /* Restore the feature counts */        i = 0;        feat_iter = list_iterator_create(detail_ptr->feature_list);        while ((feat_ptr =                    (struct feature_record *) list_next(feat_iter))) {            feat_ptr->count = feat_cnt_orig[i++];        }        list_iterator_destroy(feat_iter);        xfree(feat_cnt_orig);    } else {        /* Try to schedule the job. First on dedicated nodes         * then on shared nodes (if so configured). */        uint16_t orig_shared;        time_t now = time(NULL);        char str[100];        preemptee_candidates = slurm_find_preemptable_jobs(job_ptr);        orig_shared = job_ptr->details->shared;        job_ptr->details->shared = 0;        tmp_bitmap = bit_copy(*avail_bitmap);        if (exc_core_bitmap) {            bit_fmt(str, (sizeof(str) - 1), exc_core_bitmap);            debug2(" _try_sched with exclude core bitmap: %s",str);        }        rc = select_g_job_test(job_ptr, *avail_bitmap, min_nodes,                               max_nodes, req_nodes,                               SELECT_MODE_WILL_RUN,                               preemptee_candidates,                               &preemptee_job_list,                               exc_core_bitmap);        if (preemptee_job_list) {            list_destroy(preemptee_job_list);            preemptee_job_list = NULL;        }        job_ptr->details->shared = orig_shared;//.........这里部分代码省略.........
开发者ID:shapovalovts,项目名称:slurm,代码行数:101,


示例30: addPoint

	/**	 * /brief add a point	 */	void	addPoint(const FocusPoint& point,			const Ice::Current& /* current */) {		std::cout << timeformat("%H:%M:%S ", time(NULL));		std::cout << point.position << ": " << point.value;		std::cout << std::endl;	}
开发者ID:AndreasFMueller,项目名称:AstroPhotography,代码行数:9,



注:本文中的time函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ time2string函数代码示例
C++ tilemap_set_transparent_pen函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。