/********************************************************** * Function: controller *********************************************************/ void *controller(void *arg) { char request[10]; char answer[10]; MIXER_STATE = 0; TIME_LAST_CHANGE_MIXER = time(NULL); // Endless loop memset(request,'\0',10); memset(answer,'\0',10); struct timespec timeInit, timeEnd, timeDiff, timePeriod; timePeriod.tv_sec = (time_t) TIME_SEC_CYCLE_SECONDS; timePeriod.tv_nsec = (long) TIME_SEC_CYCLE_NANOSECONDS; while(1) { // - Lectura de la pendiente actual if(read_slope(request, answer) == 2) { printf("Error in read slope"); } // - Lectura de la velocidad actual if(read_speed(request, answer) == -1.0) { //Error printf("Error in read speed"); } // - Activar el acelerador if(gas_turn(request, answer) != 0 ) { //Error printf("Error in break. Current value = "); } // - Activar el freno if(break_turn(request, answer) != 0 ) { //Error printf("Error in break. Current value = "); } // - Activar el Mezclador if(mixer_turn(request, answer) != 0 ) { //Error printf("Error in break. Current value = "); } sec_cycle = (sec_cycle + 1) % TOTAL_SEC_CYCLES; clock_gettime(CLOCK_REALTIME, &timeEnd); diffTime(timeEnd, timeInit, &timeDiff); diffTime(timePeriod, timeDiff, &timeDiff); nanosleep(&timeDiff, NULL); addTime(timeInit, timePeriod, &timeInit); } //return (0); }
/***************************************************************************** * Function: main() *****************************************************************************/ int main() { struct timespec start,end,diff,cycle; unsigned char buf[SEND_SIZE]; int fd_file = -1; int fd_serie = -1; int ret = 0; // Uncomment to test on the Arduino //fd_serie = initSerialMod_WIN_115200 (); // Uncomment to test on the PC iniciarAudio_Windows (); /* Open music file */ printf("open file %s begin\n",FILE_NAME); fd_file = open (FILE_NAME, O_RDONLY, 0644); if (fd_file < 0) { printf("open: error opening file\n"); return -1; } // loading cycle time cycle.tv_sec=PERIOD_TASK_SEC; cycle.tv_nsec=PERIOD_TASK_NSEC; clock_gettime(CLOCK_REALTIME,&start); while (1) { // read from music file ret=read(fd_file,buf,SEND_SIZE); if (ret < 0) { printf("read: error reading file\n"); return NULL; } // write to serial port // Uncomment to test on the Arduino //ret = writeSerialMod_256 (buf); // Uncomment to test on the PC ret = reproducir_1bit_4000 (buf); if (ret < 0) { printf("write: error writting serial\n"); return NULL; } // get end time, calculate lapso and sleep clock_gettime(CLOCK_REALTIME,&end); diffTime(end,start,&diff); if (0 >= compTime(cycle,diff)) { printf("ERROR: lasted long than the cycle\n"); return NULL; } diffTime(cycle,diff,&diff); nanosleep(&diff,NULL); addTime(start,cycle,&start); } }
void logEventEnd(uint8_t posNo, const char *eventName) { struct timespec endTimestamp; if (clock_gettime(CLOCK_MONOTONIC, &endTimestamp)) { perror("logger.c: logEvent: clock_gettime failed."); exit(EXIT_FAILURE); } struct timespec runtime = diffTime(eventStartTimestamp[posNo], endTimestamp); event_t event; event.timestamp = runtime; event.name = strdup(eventName); if (logInitialised[posNo]) { event_t minEvent = logMin[posNo]; if (compareTime(runtime, minEvent.timestamp) == 2) { // if minEvent.timestamp is bigger than runtime, we found a new // minimum candidate logMin[posNo] = event; } event_t maxEvent = logMax[posNo]; if (compareTime(runtime, maxEvent.timestamp) == 1) { // if runtime is bigger than maxEvent.timestamp, we found a new // maximum candidate logMax[posNo] = event; } } else { logMin[posNo] = event; logMax[posNo] = event; logInitialised[posNo] = 1; } }
/* Compute an attractor previously allocated by newAttractor */ void computeAttractor (struct attractor *a, char *code) { struct timeval t1, t2; if (code == NULL || checkCode (code)) { explore (a); } else { strncpy (a->code, code, a->polynom->length * a->dimension + 3); applyCode (a->polynom, code); if (!isAttractorConverging (a)) fprintf (stderr, "Bad code - attractor not converging\n"); } a->polynom->sum = getPolynomSum (a->polynom); displayPolynom (a->polynom); fprintf (stdout, "Lyapunov exponent: %.6f\n", a->lyapunov->ly); gettimeofday (&t1, NULL); iterateMap (a); gettimeofday (&t2, NULL); diffTime ("Map iteration", &t1, &t2); a->r = getRadius (a); centerAttractor (a); computeDimension (a); fprintf (stdout, "Correlation dimension: %.6f\n", a->correlationDimension); fprintf (stdout, "Code: %s\n", a->code); }
NSInfo( string thens , BSONObj a , BSONObj b ) { ns = thens; prev = a; cur = b; timeDiff = diffTime( "total" ); }
/** * Stop the clock. */ inline void StopwatchBase::Stop() { if (running) { elapsedTime += diffTime(); running = false; } }
// sets diffTimeMs parameter as well (appalling...) bool waitingTooLong(struct timespec startTime, int threshold, time_t* diffTimeMs) { struct timespec endTime; clock_gettime(CLOCK_MONOTONIC, &endTime); *diffTimeMs = timespecToMs(diffTime(endTime, startTime)); if(*diffTimeMs > threshold) return true; return false; }
static void compareSnapshot(const Snapshot &from, const Snapshot &to, Entry *entry) { entry->time = diffTime(from.time, to.time); entry->memoryDiff = to.memory_curr - from.memory_curr; entry->allocTotal = to.memory_total - from.memory_total; for (int i = 0; i < 32; i++) { entry->delta_blk_cnt_curr[i] = to.blk_cnt_curr[i] - from.blk_cnt_curr[i]; entry->delta_blk_cnt_total[i] = to.blk_cnt_total[i] - from.blk_cnt_total[i]; } }
static double time_calc(int rds) { if (mpi_integrate(0, 0)) return -1; /* perform force calculation test */ markTime(); if (mpi_integrate(rds, -1)) return -1; markTime(); return diffTime()/rds; }
double time_force_calc(int default_samples) { int rds = timing_samples > 0 ? timing_samples : default_samples; int i; if (mpi_integrate(0, 0)) return -1; /* perform force calculation test */ markTime(); for (i = 0; i < rds; i++) { if (mpi_integrate(0, -1)) return -1; } markTime(); return diffTime()/rds; }
/** * Application can be start up with one parameter. * Where the param should be integer number ( exacly time in milliseconds ). * Returned value will be the difference between current time and value parameter. * IF application will be start up witchout any parameter then result will be the current time in milliseconds. * In both cases calculated results will be passed to stdout. * * Usage: * time <param | no param> * */ int main(int argc , char * argv[]){ //current time tmval ctime = getTimeOfMilli(); if(argc == 1){ printf("%ld",ctime); }else if (argc >= 2){ if(argc > 2 ){ fprintf(stderr,"Unrecognized number of input parameters [%d]. Expected 1\n",argc); } //start time tmval stime = strtoul(argv[1],NULL,0); printf("%ld", diffTime(stime,ctime) ); } return 0; }
int diffTimeMS( const char * field ) const { return (int)(diffTime( field ) / 1000); }
/** * Return the current amount of time on the clock. * This is the total amout of time that has elapsed * between Start() and Stop() pairs since the last * Reset(). */ inline float StopwatchBase::GetTime() const { if (running) return (elapsedTime + diffTime()); else return (elapsedTime); }
/* * The main method initializes the gpios and starts a thread and checks the content * of the files. */ int main() { int res; int count, statusBefore, statusAfter, sensorBefore, sensorAfter; struct timespec sleeptime, result, sensorResult; struct timespec before, measureSensorBefore; struct timespec after, measureSensorAfter; uint16_t distance; sleeptime.tv_sec = 0; sleeptime.tv_nsec = 000010000L; // sleep 10µs int maxPriority; int status; // get max available priority maxPriority = sched_get_priority_max(SCHED_FIFO); if (maxPriority == -1) { perror("Could not determine the maximum priority available."); exit(EXIT_FAILURE); } // set scheduler to SCHED_FIFO and priority to max priority struct sched_param sched; sched.sched_priority = maxPriority; status = sched_setscheduler(0, SCHED_FIFO, &sched); if (status) { perror("ERROR: Could not set real time priority (are you running this as root?)"); exit(EXIT_FAILURE); } // TODO: Add comment for the above sleeptime: How much µs / ms whatever is this? -> use human readable unit here! /*signal(SIGINT, sigfunc); */ wiringPiSetupGpio(); pinMode(GPIO_TRIGGER, OUTPUT); pinMode(GPIO_ECHO, INPUT); statusBefore = clock_gettime(CLOCK_MONOTONIC, &before); digitalWrite(GPIO_TRIGGER, 1); if(clock_nanosleep(CLOCK_MONOTONIC, 0, &sleeptime, NULL)) { perror("nanosleep failed\n"); exit(EXIT_FAILURE); } digitalWrite(GPIO_TRIGGER, 0); while(1) { if(digitalRead(GPIO_ECHO) == 1) { sensorBefore = clock_gettime(CLOCK_MONOTONIC, &measureSensorBefore); break; } } while(1) { if(digitalRead(GPIO_ECHO) == 0) { sensorAfter = clock_gettime(CLOCK_MONOTONIC, &measureSensorAfter); break; } } /* A bit of theory: * Max distance of ultrasonic sensor: about 3m * -> So the max time for the sound to travel to a barrier * and back for this distance is (at 19.2 degree celsius): * 6m / 343m/s = 0.017492711s = 17492711ns * => max number in result.tv_nsec is 17492711ns * * 17492711 * 343 = 5999999873 ==> this is the max number which must be * stored in the meantime during the calculation. * Max no to be stored: 5999999873 * Max no in long : 4294967295 * --> so we need to use an usigned *long long* in the following.. */ sensorResult = diffTime(measureSensorBefore, measureSensorAfter); distance = (uint64_t) sensorResult.tv_nsec * 343 / 1000000 / 2; statusAfter = clock_gettime(CLOCK_MONOTONIC, &after); result = diffTime(before, after); printf("seconds: %ld nanoseconds %ld\n", result.tv_sec, result.tv_nsec); printf("Result: %hu\n\n", distance); delay(20); return(EXIT_SUCCESS); }
void TTMpeg2MainWnd::analyzeMpegStream( ) { uint max_print_frames = 2500; uint i; long num_frames = 0; QString strHeaderType; QString strHeaderOffset; QString strPictureType; QString strTempRef; QString strDOrder; QString strSOrder; QString strTime; QString strOut; Q3ListViewItem* item; TTPicturesHeader* current_picture; uint num_index; double read_percent; // TODO: use QTime for timing purpose (have better resolution) time_t seconds_start; time_t seconds_end; num_frames = 0; // start time seconds_start = time( NULL ); // open the mpeg2 stream if ( !file_name.isEmpty() ) { // get the stream type and create according stream-object video_type = new TTVideoType( file_name ); // test audio_type = new TTAudioType( "rbb_test.mpa" ); if ( audio_type->avStreamType() == TTAVTypes::mpeg_audio ) { qDebug( "%sfound mpeg audio stream",cName ); TTMPEGAudioStream* audio_stream = (TTMPEGAudioStream*)audio_type->createAudioStream(); uint h_count = audio_stream->createHeaderList(); } if ( video_type->avStreamType() == TTAVTypes::mpeg2_demuxed_video ) video_stream = (TTMpeg2VideoStream*)video_type->createVideoStream(); else { qDebug("%swrong video type",cName); return; } progress_bar = new TTProgressBar( this ); video_stream->setProgressBar( progress_bar ); progress_bar->show(); qApp->processEvents(); // create header- and index-list video_stream->createHeaderList(); num_index = video_stream->createIndexList(); qDebug("%snum index: %d",cName,num_index); // get pointer to the lists index_list = video_stream->indexList(); header_list = video_stream->headerList(); // get pointer to stream mpeg2_stream = video_stream->streamBuffer(); // sort frame index list to display (decoder) order index_list->sortDisplayOrder(); // get end time seconds_end = time( NULL ); setReadTime( diffTime( seconds_start, seconds_end ) ); // print out statistic informations // get stream length and set label text setFileLength( mpeg2_stream->streamLength() ); read_percent = (double)mpeg2_stream->readCount()/(double)mpeg2_stream->streamLength()*100.0; setReadOps( mpeg2_stream->readCount(), read_percent ); setFillOps( mpeg2_stream->fillCount() ); // print out the number of frames in stream num_frames = index_list->count(); total_time = ttFramesToTime( num_frames, 25.0 ); setNumFramesTotal( num_frames ); setNumIFrames( index_list->numIFrames() ); setNumPFrames( index_list->numPFrames() ); setNumBFrames( index_list->numBFrames() ); setNumSequence( header_list->numSequenceHeader() ); setNumPicture( header_list->numPictureHeader() ); setNumGOP( header_list->numGopHeader() ); setNumSequenceEnd( header_list->numSequenceEndHeader() ); if ( video_stream->indexList()->count() < max_print_frames ) max_print_frames = video_stream->indexList()->count(); // print out the frame list; print maximal 1000 rows (!) for( i = 0; i < max_print_frames; i++ ) { item = new Q3ListViewItem( lvStreamInfo ); strDOrder.sprintf("%08ld",index_list->displayOrder(i)); strSOrder.sprintf("%08ld",index_list->streamOrder(i)); strHeaderType.sprintf("0x%02x",header_list->at(index_list->headerListIndex(i))->headerType()); strHeaderOffset.sprintf("%12ld",header_list->at(index_list->headerListIndex(i))->headerOffset()); current_picture = (TTPicturesHeader*)header_list->at(index_list->headerListIndex(i)); switch(index_list->videoIndexAt(i)->picture_coding_type) { case(1): strPictureType.sprintf("I-Frame"); strTempRef.sprintf("%04d",current_picture->temporal_reference); break; case(2): strPictureType.sprintf("P-Frame"); strTempRef.sprintf("%04d",current_picture->temporal_reference); break; case(3): strPictureType.sprintf("B-Frame"); strTempRef.sprintf("%04d",current_picture->temporal_reference); break; } num_frames++; item->setText( 0, strHeaderType ); item->setText( 1, strHeaderOffset ); item->setText( 2, strPictureType ); item->setText( 3, strTempRef ); item->setText( 4, strSOrder ); item->setText( 5, strDOrder ); strTime.sprintf("%s,%d",ttFramesToTime(index_list->displayOrder(i),25.0).toString().ascii(), ttFramesToTime(index_list->displayOrder(i),25.0).msec()); item->setText( 6, strTime ); } // delete the progress bar delete progress_bar; video_stream->setProgressBar( NULL ); sbFrames->setMinValue( 0 ); sbFrames->setMaxValue( index_list->count()-1 ); slider_update = false; sbFrames->setValue( 0 ); // show information about the first frame showFrame( 0 ); mpeg2_window->openVideoFile( file_name, index_list, header_list ); mpeg2_window->resize( 400, 350 ); mpeg2_window->moveToFirstFrame( true ); } }
int main ( ) { Chars errMsg; FreeGroup F; cout << "Enter a free group: "; errMsg = cin >> F; if( errMsg.length() > 0 ) { cout << errMsg; exit(0); } cout << endl; VectorOf<Chars> empty, varNames; EquationParser p(cin); cout << "Enter a graphic equation: "; Word equation = p.parseEquation(empty, varNames, errMsg); if( errMsg.length() > 0 ) { cout << errMsg; exit(0); } cout << endl; cout << "Enter a word in F: "; WordParser P(cin); Word w = P.parseWordVerbatim( F.namesOfGenerators(), errMsg); if( errMsg.length() > 0 ) { cout << errMsg; exit(0); } cout << endl; w = w.cyclicallyReduce(); FreeGroup G(varNames); cout << "The group: " << F << endl; cout << "The variables: " << varNames << endl; cout << "Equation: "; G.printWord(cout, equation); cout << endl; cout << "Constant of length " << w.length() << ": "; F.printWord(cout, w); cout << endl; DGESolver solver(F,varNames,equation); Map solution; int wLen = w.length(); timeval t1,t2; gettimeofday(&t1, NULL); for( int i = 0; i < wLen; ++i ) { Word u = w.cyclicallyPermute(i); cout << i << ": " << endl; if( solver.getSolution(u, solution) ) { cout << "The solution is: " << endl; for( int j = 0; j < varNames.length(); ++j ) { cout << varNames[j] << " = "; F.printWord(cout, solution.generatingImages(j)); cout << endl; } cout << endl; break; } else cout << "The equation has no solutions" << endl; } gettimeofday(&t2, NULL); cout << "Time elapsed: " << diffTime(t2,t1) << endl << endl; }
/** * @brief Entry point of the user-defined function for pg_bulkload. * @return Returns number of loaded tuples. If the case of errors, -1 will be * returned. */ Datum pg_bulkload(PG_FUNCTION_ARGS) { Reader *rd = NULL; Writer *wt = NULL; Datum options; MemoryContext ctx; MemoryContext ccxt; PGRUsage ru0; PGRUsage ru1; int64 count; int64 parse_errors; int64 skip; WriterResult ret; char *start; char *end; float8 system; float8 user; float8 duration; TupleDesc tupdesc; Datum values[PG_BULKLOAD_COLS]; bool nulls[PG_BULKLOAD_COLS]; HeapTuple result; /* Build a tuple descriptor for our result type */ if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE) elog(ERROR, "return type must be a row type"); BULKLOAD_PROFILE_PUSH(); pg_rusage_init(&ru0); /* must be the super user */ if (!superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("must be superuser to use pg_bulkload"))); options = PG_GETARG_DATUM(0); ccxt = CurrentMemoryContext; /* * STEP 1: Initialization */ /* parse options and create reader and writer */ ParseOptions(options, &rd, &wt, ru0.tv.tv_sec); /* initialize reader */ ReaderInit(rd); /* * We need to split PG_TRY block because gcc optimizes if-branches with * longjmp codes too much. Local variables initialized in either branch * cannot be handled another branch. */ PG_TRY(); { /* truncate heap */ if (wt->truncate) TruncateTable(wt->relid); /* initialize writer */ WriterInit(wt); /* initialize checker */ CheckerInit(&rd->checker, wt->rel, wt->tchecker); /* initialize parser */ ParserInit(rd->parser, &rd->checker, rd->infile, wt->desc, wt->multi_process, PG_GET_COLLATION()); } PG_CATCH(); { if (rd) ReaderClose(rd, true); if (wt) WriterClose(wt, true); PG_RE_THROW(); } PG_END_TRY(); /* No throwable codes here! */ PG_TRY(); { /* create logger */ CreateLogger(rd->logfile, wt->verbose, rd->infile[0] == ':'); start = timeval_to_cstring(ru0.tv); LoggerLog(INFO, "\npg_bulkload %s on %s\n\n", PG_BULKLOAD_VERSION, start); ReaderDumpParams(rd); WriterDumpParams(wt); LoggerLog(INFO, "\n"); BULKLOAD_PROFILE(&prof_init); /* * STEP 2: Build heap */ /* Switch into its memory context */ Assert(wt->context); ctx = MemoryContextSwitchTo(wt->context); /* Loop for each input file record. */ while (wt->count < rd->limit) { HeapTuple tuple; CHECK_FOR_INTERRUPTS(); /* read tuple */ BULKLOAD_PROFILE_PUSH(); tuple = ReaderNext(rd); BULKLOAD_PROFILE_POP(); BULKLOAD_PROFILE(&prof_reader); if (tuple == NULL) break; /* write tuple */ BULKLOAD_PROFILE_PUSH(); WriterInsert(wt, tuple); wt->count += 1; BULKLOAD_PROFILE_POP(); BULKLOAD_PROFILE(&prof_writer); MemoryContextReset(wt->context); BULKLOAD_PROFILE(&prof_reset); } MemoryContextSwitchTo(ctx); /* * STEP 3: Finalize heap and merge indexes */ count = wt->count; parse_errors = rd->parse_errors; /* * close writer first and reader second because shmem_exit callback * is managed by a simple stack. */ ret = WriterClose(wt, false); wt = NULL; skip = ReaderClose(rd, false); rd = NULL; } PG_CATCH(); { ErrorData *errdata; MemoryContext ecxt; ecxt = MemoryContextSwitchTo(ccxt); errdata = CopyErrorData(); LoggerLog(INFO, "%s\n", errdata->message); FreeErrorData(errdata); /* close writer first, and reader second */ if (wt) WriterClose(wt, true); if (rd) ReaderClose(rd, true); MemoryContextSwitchTo(ecxt); PG_RE_THROW(); } PG_END_TRY(); count -= ret.num_dup_new; LoggerLog(INFO, "\n" " " int64_FMT " Rows skipped.\n" " " int64_FMT " Rows successfully loaded.\n" " " int64_FMT " Rows not loaded due to parse errors.\n" " " int64_FMT " Rows not loaded due to duplicate errors.\n" " " int64_FMT " Rows replaced with new rows.\n\n", skip, count, parse_errors, ret.num_dup_new, ret.num_dup_old); pg_rusage_init(&ru1); system = diffTime(ru1.ru.ru_stime, ru0.ru.ru_stime); user = diffTime(ru1.ru.ru_utime, ru0.ru.ru_utime); duration = diffTime(ru1.tv, ru0.tv); end = timeval_to_cstring(ru1.tv); memset(nulls, 0, sizeof(nulls)); values[0] = Int64GetDatum(skip); values[1] = Int64GetDatum(count); values[2] = Int64GetDatum(parse_errors); values[3] = Int64GetDatum(ret.num_dup_new); values[4] = Int64GetDatum(ret.num_dup_old); values[5] = Float8GetDatumFast(system); values[6] = Float8GetDatumFast(user); values[7] = Float8GetDatumFast(duration); LoggerLog(INFO, "Run began on %s\n" "Run ended on %s\n\n" "CPU %.2fs/%.2fu sec elapsed %.2f sec\n", start, end, system, user, duration); LoggerClose(); result = heap_form_tuple(tupdesc, values, nulls); BULKLOAD_PROFILE(&prof_fini); BULKLOAD_PROFILE_POP(); BULKLOAD_PROFILE_PRINT(); PG_RETURN_DATUM(HeapTupleGetDatum(result)); }
void getInodeCreateTimes(struct sub3_data *inodeCreate, char **dname, char **fname, int numdirs, int numFiles) { char **flink; int fd; int i, j, index; int startTime, endTime; struct alfs_stat buf; #ifdef DEBUG printf("InodeCreateTime\n"); #endif /* name files */ flink = (char **) myMalloc (sizeof(char *) * numFiles); index = 0; i = numdirs - numFiles / MAXNUMFILESINDIR; if (numFiles % MAXNUMFILESINDIR != 0) i--; for (; i < numdirs && index < numFiles; i++) { for (j = 0; (j < MAXNUMFILESINDIR) && (index < numFiles); j++) { flink[index] = (char *) myMalloc(strlen(dname[i]) + 25); sprintf(flink[index], "%s/link%d.%d", dname[i], index, getpid()); index++; } } /* loop _reps_ time to increase accuracy */ for (j = 0; j < reps; j++) { /* flush caches */ flushAll(); /* stat the directories */ for (i = 0; i < numdirs; i++) if (stat(dname[i], &buf) == -1) { perror("inodeCreate, dir stat"); exit(1); } /* create the files */ gettimeofday(&startTime, (struct timezone *) NULL); for (i = 0; i < numFiles; i++) { if ((fd = open(fname[i], O_RDWR | O_CREAT | O_TRUNC, S_IRWXU)) == -1) { perror("inodeCreate, create"); exit(1); } close(fd); } gettimeofday(&endTime, (struct timezone *) NULL); inodeCreate->time1[j] = diffTime(startTime, endTime); #ifdef DEBUG printf("numFiles: %d, time: %f\n", numFiles, inodeCreate->time1[j]); #endif /* flush caches */ flushAll(); /* stat the files */ gettimeofday(&startTime, (struct timezone *) NULL); for (i = 0; i < numFiles; i++) if (stat(fname[i], &buf) == -1) { perror("inodeCreate, file stat"); exit(1); } gettimeofday(&endTime, (struct timezone *) NULL); inodeCreate->time2[j] = diffTime(startTime, endTime); #ifdef DEBUG printf("numFiles, %d, time: %f\n", numFiles, inodeCreate->time2[j]); #endif /* flush caches */ flushAll(); #ifndef NOHARDLINKS /* create the hard-links */ gettimeofday(&startTime, (struct timezone *) NULL); for (i = 0; i < numFiles; i++) { if (stat(fname[i], &buf) == -1) { perror("inodeCreate, file stat 2"); exit(1); } if (link(fname[i], flink[i]) == -1) { perror("inodeCreate, link"); exit(1); } } gettimeofday(&endTime, (struct timezone *) NULL); inodeCreate->time3[j] = diffTime(startTime, endTime); #ifdef DEBUG printf("numLinks: %d, time: %f\n", numFiles, inodeCreate->time3[j]); #endif #endif /* NOHARDLINKS */ /* remove everything */ for (i = 0; i < numFiles; i++) { #ifndef NOHARDLINKS if (unlink(flink[i]) < 0) { perror("inodeCreateTime, unlink link"); exit(1); } #endif if (unlink(fname[i]) < 0) { perror("inodeCreateTime, unlink"); exit(1); } } sync(); } for (i = 0; i < numFiles; i++) free(flink[i]); free(flink); }
void getDirCreateTimes(struct sub_data *dirCreate, char **dname, char **fname, int numdirs, int numFiles) { int fd, i, j; int startTime, endTime; #ifdef DEBUG printf("DirCreateTime\n"); #endif for (j = 0; j < reps; j++) { /* flush caches */ flushAll(); /* create the files */ gettimeofday(&startTime, (struct timezone *) NULL); for (i = 0; i < numFiles; i++) { if ((fd = open(fname[i], O_RDWR | O_CREAT | O_TRUNC, S_IRWXU)) == -1) { perror("dirCreate, create"); exit(1); } close(fd); } gettimeofday(&endTime, (struct timezone *) NULL); dirCreate->time1[j] = diffTime(startTime, endTime); #ifdef DEBUG printf("numFiles: %d, time: %f\n", numFiles, dirCreate->time1[j]); #endif /* remove the files */ for (i = 0; i < numFiles; i++) { if (unlink(fname[i]) < 0) { perror("dirCreateTime, unlink"); exit(1); } } sync(); /* flush caches */ flushAll(); /* create the directories */ gettimeofday(&startTime, (struct timezone *) NULL); for (i = 0; i < numFiles; i++) { if (mkdir(fname[i], S_IRWXU) == -1) { perror("dirCreate, mkdir"); exit(1); } } gettimeofday(&endTime, (struct timezone *) NULL); dirCreate->time2[j] = diffTime(startTime, endTime); #ifdef DEBUG printf("numDirs: %d, time: %f\n", numFiles, dirCreate->time2[j]); #endif /* remove the files */ for (i = 0; i < numFiles; i++) { if (rmdir(fname[i]) < 0) { perror("dirCreateTime, rmdir"); exit(1); } } sync(); } }
void getInodeAccessTimes(struct sub_data *inodeAccess, char **dname, char **fname, int numdirs, int numFiles) { int *perm; int fd, i, j; int startTime, endTime; struct alfs_stat buf; #ifdef DEBUG printf("InodeAccessTime\n"); #endif perm = (int *) myMalloc (sizeof(int) * numFiles); /* create the files */ for (i = 0; i < numFiles; i++) { if ((fd = open(fname[i], O_RDWR | O_CREAT | O_TRUNC, S_IRWXU)) == -1) { perror("inodeAccess, create"); exit(1); } close(fd); } for (j = 0; j < reps; j++) { /* create permuation */ createPerm(&perm, numFiles, 1, numFiles); /* flush buffers */ flushAll(); /* stat the path to get the path into the cache */ for (i = 0; i < numdirs; i++) if (stat(dname[i], &buf) < 0) { perror("inodeAccess, stat path"); exit(1); } /* stat in creation order */ gettimeofday(&startTime, (struct timezone *) NULL); for (i = 0; i < numFiles; i++) { if (stat(fname[i], &buf) < 0) { perror("inodeAccess, stat seq"); exit(1); } } gettimeofday(&endTime, (struct timezone *) NULL); inodeAccess->time1[j] = diffTime(startTime, endTime); #ifdef DEBUG printf("SEQ: numFiles: %d, time: %f\n", numFiles, inodeAccess->time1[j]); #endif /* flush buffers */ flushAll(); /* stat the path to get the path into the cache */ for (i = 0; i < numdirs; i++) if (stat(dname[i], &buf) < 0) { perror("inodeAccess, stat path 2"); exit(1); } /* stat in random order */ gettimeofday(&startTime, (struct timezone *) NULL); for (i = 0; i < numFiles; i++) { if (stat(fname[perm[i]], &buf) < 0) { perror("inodeAccess, stat rand"); exit(1); } } gettimeofday(&endTime, (struct timezone *) NULL); inodeAccess->time2[j] = diffTime(startTime, endTime); #ifdef DEBUG printf("RAND: numFiles: %d, time: %f\n", numFiles, inodeAccess->time2[j]); #endif } /* clean-up */ for (i = 0; i < numFiles; i++) if (unlink(fname[i]) < 0) { perror("inodeAccessTime, unlink"); exit(1); } free(perm); }
double radixSort(cl_mem& d_source, int length, PlatInfo info) { double totalTime = 0; int blockSize = 47; //local memory size: 47KB int gridSize = 64; cl_int status; int argsNum = 0; int bits = 8; //each pass sort 8 bits int radix = (1<<bits); uint hisSize = blockSize * gridSize * radix; uint isExclusive = 1; //kernel reading char sortPath[100] = PROJECT_ROOT; strcat(sortPath, "/Kernels/radixSortKernel.cl"); std::string sortKerAddr = sortPath; char countHisSource[100] = "countHis"; char writeHisSource[100] = "writeHis"; KernelProcessor sortReader(&sortKerAddr,1,info.context); cl_kernel countHisKernel = sortReader.getKernel(countHisSource); cl_kernel writeHisKernel = sortReader.getKernel(writeHisSource); size_t testLocal[1] = {(size_t)blockSize}; size_t testGlobal[1] = {(size_t)(blockSize * gridSize)}; struct timeval start, end; cl_mem d_temp = clCreateBuffer(info.context, CL_MEM_READ_WRITE, sizeof(Record)*length, NULL, &status); checkErr(status, ERR_HOST_ALLOCATION); cl_mem d_histogram = clCreateBuffer(info.context, CL_MEM_READ_WRITE, sizeof(uint)* hisSize, NULL, &status); checkErr(status, ERR_HOST_ALLOCATION); cl_mem d_loc = clCreateBuffer(info.context, CL_MEM_READ_WRITE, sizeof(uint)*length, NULL, &status); checkErr(status, ERR_HOST_ALLOCATION); for(uint shiftBits = 0; shiftBits < sizeof(int) * 8; shiftBits += bits) { isExclusive = 1; //reset the exclusive //data preparation argsNum = 0; status |= clSetKernelArg(countHisKernel, argsNum++, sizeof(cl_mem), &d_source); status |= clSetKernelArg(countHisKernel, argsNum++, sizeof(int), &length); status |= clSetKernelArg(countHisKernel, argsNum++, sizeof(cl_mem), &d_histogram); status |= clSetKernelArg(countHisKernel, argsNum++, sizeof(ushort)*radix*blockSize, NULL); status |= clSetKernelArg(countHisKernel, argsNum++, sizeof(uint), &shiftBits); checkErr(status, ERR_SET_ARGUMENTS); #ifdef PRINT_KERNEL printExecutingKernel(countHisKernel); #endif gettimeofday(&start, NULL); status = clEnqueueNDRangeKernel(info.currentQueue, countHisKernel, 1, 0, testGlobal, testLocal, 0, 0, 0); status = clFinish(info.currentQueue); gettimeofday(&end, NULL); checkErr(status, ERR_EXEC_KERNEL); totalTime += diffTime(end, start); totalTime += scan(d_histogram,hisSize,1,info); argsNum = 0; status |= clSetKernelArg(writeHisKernel, argsNum++, sizeof(cl_mem), &d_source); status |= clSetKernelArg(writeHisKernel, argsNum++, sizeof(uint), &length); status |= clSetKernelArg(writeHisKernel, argsNum++, sizeof(cl_mem), &d_histogram); status |= clSetKernelArg(writeHisKernel, argsNum++, sizeof(cl_mem), &d_loc); status |= clSetKernelArg(writeHisKernel, argsNum++, sizeof(uint)*radix*blockSize, NULL); status |= clSetKernelArg(writeHisKernel, argsNum++, sizeof(uint), &shiftBits); checkErr(status, ERR_SET_ARGUMENTS); #ifdef PRINT_KERNEL printExecutingKernel(writeHisKernel); #endif gettimeofday(&start, NULL); status = clEnqueueNDRangeKernel(info.currentQueue, writeHisKernel, 1, 0, testGlobal, testLocal, 0, 0, 0); status = clFinish(info.currentQueue); gettimeofday(&end, NULL); checkErr(status, ERR_EXEC_KERNEL); totalTime += diffTime(end, start); //scatter totalTime += scatter(d_source, d_temp, length, d_loc, 512, 32768, info); //copy the buffer for another loop status = clEnqueueCopyBuffer(info.currentQueue, d_temp, d_source, 0, 0, sizeof(Record)*length,0 , 0, 0); checkErr(status, ERR_COPY_BUFFER); } status = clReleaseMemObject(d_temp); checkErr(status, ERR_RELEASE_MEM); status = clReleaseMemObject(d_histogram); checkErr(status, ERR_RELEASE_MEM); status = clReleaseMemObject(d_loc); checkErr(status, ERR_RELEASE_MEM); return totalTime; }
int main(int argc, char *argv[]) { struct timespec lastSent, timeNow, lastReceived, timeDiff; struct timeval timeout; int max_fd, vsc_fd, retval; int16_t testvalue; char teststring[20]; fd_set input; testvalue = -1234; /* Verify Arguments */ if (argc != 3) { printf("Usage - program SerialPort BaudRate\n"); printf("\t%s /dev/ttyUSB0 115200\n", argv[0]); exit(EXIT_FAILURE); } /* Catch CTRL-C */ signal(SIGINT, signal_handler); /* Open VSC Interface */ vscInterface = vsc_initialize(argv[1], atoi(argv[2])); if (vscInterface == NULL) { printf("Opening VSC Interface failed.\n"); exit(EXIT_FAILURE); } /* Initialize the input set */ vsc_fd = vsc_get_fd(vscInterface); FD_ZERO(&input); FD_SET(vsc_fd, &input); max_fd = vsc_fd + 1; /* Reset timing values to the current time */ clock_gettime(CLOCK_REALTIME, &lastSent); clock_gettime(CLOCK_REALTIME, &lastReceived); /* Send Heartbeat Message to VSC */ vsc_send_heartbeat(vscInterface, ESTOP_STATUS_NOT_SET); /* Send Display Mode to VSC */ vsc_send_user_feedback(vscInterface, VSC_USER_DISPLAY_MODE, DISPLAY_MODE_CUSTOM_TEXT); /* Send User String Values Once to VSC */ vsc_send_user_feedback_string(vscInterface, VSC_USER_DISPLAY_ROW_1, "DISPLAY MODE TEST "); vsc_send_user_feedback_string(vscInterface, VSC_USER_DISPLAY_ROW_2, "ABCDEFGHIJKLMNOPQRST"); vsc_send_user_feedback_string(vscInterface, VSC_USER_DISPLAY_ROW_3, "12345678901234567890"); /* Loop Forever */ while (1) { /* Get current clock time */ clock_gettime(CLOCK_REALTIME, &timeNow); /* Send Heartbeat messages every 50 Milliseconds (20 Hz) */ if (diffTime(lastSent, timeNow, &timeDiff) > 50000) { /* Get current clock time */ lastSent = timeNow; /* Send Heartbeat */ vsc_send_heartbeat(vscInterface, ESTOP_STATUS_NOT_SET); /* Send 4th display row */ /* NOTE: One text string is only passed to the SRC every 250ms * no matter how fast the messages are sent to the VSC. */ testvalue++; sprintf(teststring,"test: %07i",testvalue); vsc_send_user_feedback_string(vscInterface, VSC_USER_DISPLAY_ROW_4, teststring); } /* Initialize the timeout structure for 50 milliseconds*/ timeout.tv_sec = 0; timeout.tv_usec = (50000 - (diffTime(lastSent, timeNow, &timeDiff) * .001)); /* Perform select on serial port or Timeout */ FD_ZERO(&input); FD_SET(vsc_fd, &input); max_fd = vsc_fd + 1; retval = select(max_fd, &input, NULL, NULL, &timeout); /* See if there was an error */ if (retval < 0) { fprintf(stderr, "vsc_example: select failed"); } else if (retval == 0) { /* No data received - Check to see when we last recieved data from the VSC */ clock_gettime(CLOCK_REALTIME, &timeNow); diffTime(lastReceived, timeNow, &timeDiff); if(timeDiff.tv_sec > 0) { printf("vsc_example: WARNING: No data received from VSC in %li.%09li seconds!\n", timeDiff.tv_sec, timeDiff.tv_nsec); } } else { /* Input received, check to see if its from the VSC */ if (FD_ISSET(vsc_fd, &input)) { /* Read from VSC */ readFromVsc(); /* Record the last time input was recieved from the VSC */ clock_gettime(CLOCK_REALTIME, &lastReceived); } else { fprintf(stderr, "vsc_example: invalid fd set"); } } } /* Clean up */ printf("Shutting down.\n"); vsc_cleanup(vscInterface); return 0; }
double ninlj(cl_mem& d_R, int rLen, cl_mem& d_S, int sLen, cl_mem& d_Out, int & oLen, PlatInfo info, int localSize, int gridSize) { double totalTime = 0; //number of result joined records int itemNum = localSize * gridSize; int locald_S_Length = 0; //actual number of records in a block local memory int pass = 0; int calLocalSLength = ceil(1.0 * sLen / gridSize); //calculate how many records should one block store in local memory if (calLocalSLength * sizeof(Record) > MAX_LOCAL_MEM_SIZE) { locald_S_Length = MAX_LOCAL_MEM_SIZE / sizeof(Record); pass = ceil( sLen * 1.0 / ( gridSize * locald_S_Length ) ); } else { locald_S_Length = calLocalSLength; pass = 1; } int countNum = itemNum * pass; uint tempCount = 0; cl_int status = 0; int argsNum = 0; int totalResNum = 0; //kernel reading char ninljPath[100] = PROJECT_ROOT; strcat(ninljPath, "/Kernels/ninljKernel.cl"); std::string ninljKerAddr = ninljPath; char countMatchSource[100] = "countMatch"; char writeMatchSource[100] = "writeMatch"; KernelProcessor ninljReader(&ninljKerAddr,1,info.context); cl_kernel countMatchKernel = ninljReader.getKernel(countMatchSource); cl_kernel writeMatchKernel = ninljReader.getKernel(writeMatchSource); //memory allocation cl_mem d_count = clCreateBuffer(info.context, CL_MEM_READ_WRITE, sizeof(uint)*countNum, NULL, &status); checkErr(status, ERR_HOST_ALLOCATION); //set work group and NDRange sizes size_t mylocal[1] = {(size_t)localSize}; size_t global[1] = {(size_t)(localSize * gridSize)}; struct timeval start, end; for(int tempPass = 0; tempPass < pass; tempPass++) { //set kernel arguments argsNum = 0; status |= clSetKernelArg(countMatchKernel, argsNum++, sizeof(cl_mem), &d_R); status |= clSetKernelArg(countMatchKernel, argsNum++, sizeof(int), &rLen); status |= clSetKernelArg(countMatchKernel, argsNum++, sizeof(cl_mem), &d_S); status |= clSetKernelArg(countMatchKernel, argsNum++, sizeof(int), &sLen); status |= clSetKernelArg(countMatchKernel, argsNum++, sizeof(cl_mem), &d_count); status |= clSetKernelArg(countMatchKernel, argsNum++, sizeof(Record)*locald_S_Length, NULL); status |= clSetKernelArg(countMatchKernel, argsNum++, sizeof(int), &locald_S_Length); status |= clSetKernelArg(countMatchKernel, argsNum++, sizeof(uint)*localSize, NULL); status |= clSetKernelArg(countMatchKernel, argsNum++, sizeof(int), &tempPass); checkErr(status, ERR_SET_ARGUMENTS); //launch the kernel #ifdef PRINT_KERNEL printExecutingKernel(countMatchKernel); #endif gettimeofday(&start, NULL); status = clEnqueueNDRangeKernel(info.currentQueue, countMatchKernel, 1, 0, global, mylocal, 0, 0, 0); status = clFinish(info.currentQueue); gettimeofday(&end, NULL); totalTime += diffTime(end, start); checkErr(status, ERR_EXEC_KERNEL); } //get the last num status = clEnqueueReadBuffer(info.currentQueue, d_count, CL_TRUE, sizeof(uint)*(countNum-1), sizeof(uint), &tempCount, 0, 0, 0); checkErr(status, ERR_READ_BUFFER); totalResNum += tempCount; //scan totalTime += scan(d_count, countNum, 1, info); //get the last number status = clEnqueueReadBuffer(info.currentQueue, d_count, CL_TRUE,sizeof(uint)*(countNum-1), sizeof(uint), &tempCount, 0, NULL, NULL); checkErr(status, ERR_READ_BUFFER); totalResNum += tempCount; oLen = totalResNum; if (totalResNum == 0) { return totalTime; } d_Out = clCreateBuffer(info.context, CL_MEM_WRITE_ONLY, sizeof(Record)*totalResNum, NULL, &status); checkErr(status, ERR_HOST_ALLOCATION); //write count for(int tempPass = 0; tempPass < pass; tempPass++) { //set kernel arguments argsNum = 0; status |= clSetKernelArg(writeMatchKernel, argsNum++, sizeof(cl_mem), &d_R); status |= clSetKernelArg(writeMatchKernel, argsNum++, sizeof(int), &rLen); status |= clSetKernelArg(writeMatchKernel, argsNum++, sizeof(cl_mem), &d_S); status |= clSetKernelArg(writeMatchKernel, argsNum++, sizeof(int), &sLen); status |= clSetKernelArg(writeMatchKernel, argsNum++, sizeof(cl_mem), &d_Out); status |= clSetKernelArg(writeMatchKernel, argsNum++, sizeof(cl_mem), &d_count); status |= clSetKernelArg(writeMatchKernel, argsNum++, sizeof(Record)*locald_S_Length, NULL); status |= clSetKernelArg(writeMatchKernel, argsNum++, sizeof(int), &locald_S_Length); status |= clSetKernelArg(writeMatchKernel, argsNum++, sizeof(uint)*localSize, NULL); status |= clSetKernelArg(writeMatchKernel, argsNum++, sizeof(int), &tempPass); checkErr(status, ERR_SET_ARGUMENTS); //launch the kernel #ifdef PRINT_KERNEL printExecutingKernel(writeMatchKernel); #endif gettimeofday(&start, NULL); status = clEnqueueNDRangeKernel(info.currentQueue, writeMatchKernel, 1, 0, global, mylocal, 0, 0, 0); status = clFinish(info.currentQueue); gettimeofday(&end, NULL); totalTime += diffTime(end, start); checkErr(status, ERR_EXEC_KERNEL); } return totalTime; }
int main(int argc, char *argv[]) { struct timespec lastSent, timeNow, lastReceived, timeDiff; struct timeval timeout; int max_fd, vsc_fd, retval; fd_set input; /* Verify Arguments */ if (argc != 3) { printf("Usage - program SerialPort BaudRate\n"); printf("\t%s /dev/ttyUSB0 115200\n", argv[0]); exit(EXIT_FAILURE); } /* Catch CTRL-C */ signal(SIGINT, signal_handler); /* Open VSC Interface */ vscInterface = vsc_initialize(argv[1], atoi(argv[2])); if (vscInterface == NULL) { printf("Opening VSC Interface failed.\n"); exit(EXIT_FAILURE); } /* Initialize the input set */ vsc_fd = vsc_get_fd(vscInterface); FD_ZERO(&input); FD_SET(vsc_fd, &input); max_fd = vsc_fd + 1; /* Reset timing values to the current time */ clock_gettime(CLOCK_REALTIME, &lastSent); clock_gettime(CLOCK_REALTIME, &lastReceived); /* Send Heartbeat Message to VSC */ vsc_send_heartbeat(vscInterface, ESTOP_STATUS_NOT_SET); /* Loop Forever */ while (1) { /* Get current clock time */ clock_gettime(CLOCK_REALTIME, &timeNow); /* Send Heartbeat messages every 50 Milliseconds (20 Hz) */ if (diffTime(lastSent, timeNow, &timeDiff) > 50000) { /* Get current clock time */ lastSent = timeNow; /* Send Heartbeat */ vsc_send_heartbeat(vscInterface, ESTOP_STATUS_NOT_SET); } /* Initialize the timeout structure for 50 milliseconds*/ timeout.tv_sec = 0; timeout.tv_usec = (50000 - (diffTime(lastSent, timeNow, &timeDiff) * .001)); /* Perform select on serial port or Timeout */ FD_ZERO(&input); FD_SET(vsc_fd, &input); max_fd = vsc_fd + 1; retval = select(max_fd, &input, NULL, NULL, &timeout); /* See if there was an error */ if (retval < 0) { fprintf(stderr, "vsc_example: select failed"); } else if (retval == 0) { /* No data received - Check to see when we last recieved data from the VSC */ clock_gettime(CLOCK_REALTIME, &timeNow); diffTime(lastReceived, timeNow, &timeDiff); if(timeDiff.tv_sec > 0) { printf("vsc_example: WARNING: No data received from VSC in %li.%09li seconds!\n", timeDiff.tv_sec, timeDiff.tv_nsec); } } else { /* Input received, check to see if its from the VSC */ if (FD_ISSET(vsc_fd, &input)) { /* Read from VSC */ readFromVsc(); /* Record the last time input was recieved from the VSC */ clock_gettime(CLOCK_REALTIME, &lastReceived); } else { fprintf(stderr, "vsc_example: invalid fd set"); } } } /* Clean up */ printf("Shutting down.\n"); vsc_cleanup(vscInterface); return 0; }