Example #1
0
int main()
{
  Stopwatch sw;
  sw.restart();
  int maxtime = 2;
  while(sw.getTime()<maxtime) {
    printf("%f \n",sw.getTime());
  }
  sw.stop();
  printf("end time = %f \n",sw.getTime());
} 
Example #2
0
float BenchmarkCPU::runCPUBenchmark(int iters, int n1, int n2)
{
    ArraySumUtil hope;
    Stopwatch sw;


    //Testing the GPU class

    float **h_xx = (float**)malloc(sizeof(float*)*n1);
    float **h_yy = (float**)malloc(sizeof(float*)*n1);

    for(int i = 0; i<n1; i++) {
        h_xx[i] = (float*)malloc(sizeof(float)*n2);
        h_yy[i] = (float*)malloc(sizeof(float)*n2);

        //Initializing the arrays.
        for(int j = 0; j<n2; j++) {

            h_xx[i][j] = i+j;
            h_yy[i][j] = i+j;

        }

    }

    int maxTime = 5;
    int count = 0;

    sw.restart();
    while (sw.getTime() < maxTime) {
        hope.arraySumCPULoop(h_xx, h_yy, n1, n2, iters);
        count++;
        std::cout << sw.getTime() << std::endl;

    }
    sw.stop();

    float n1f = (float) n1;
    float n2f = (float) n2;
    float countf = (float) count;

    float mflops = n1f*n2f*countf*iters*1.0e-06/sw.getTime();

    //std::cout << "Number of MegaFLOPs: " << n1f*n2f*500*countf*1.0e-6 << std::endl;
    std::cout << mflops << " MegaFLOPS" << std::endl;

    return mflops;

}
Example #3
0
bool
CondVarBase::wait(Stopwatch& timer, double timeout) const
{
    double remain = timeout-timer.getTime();
    // Some ARCH wait()s return prematurely, retry until really timed out
    // In particular, ArchMultithreadPosix::waitCondVar() returns every 100ms
    do {
        // Always call wait at least once, even if remain is 0, to give
        // other thread a chance to grab the mutex to avoid deadlocks on
        // busy waiting.
        if (remain<0.0) remain=0.0;
        if (wait(remain))
            return true;
        remain = timeout - timer.getTime();
    } while (remain >= 0.0);
    return false;
}
Example #4
0
bool
CondVarBase::wait(Stopwatch& timer, double timeout) const
{
	// check timeout against timer
	if (timeout >= 0.0) {
		timeout -= timer.getTime();
		if (timeout < 0.0)
			return false;
	}
	return wait(timeout);
}
Example #5
0
 void InternalThreadEntry() {
     Stopwatch timer;
     timer.start();
     for(int j = 0; j<this->n; j++) {
         if(this->A[this->i][j]) {
             for(int k = 0; k<this->n; k++) {
                 if(this->A[this->i][k] && A[j][k]) this->t++;
             }
         }
     }
     timer.stop();
     this->time = timer.getTime();
 }
TestCase * Grader07::testSpellCheck(std::string filename)
{
  Commands07 cmds07;
  std::vector<std::string> words;
  std::vector<SpellCheckCmd> commands;

  cmds07.readReads("words", words);
  cmds07.loadSpellCheckCommands(filename, commands);

  if(words.size() == 0){
    return failed("cannot read input file #1");
  }

  if(commands.size() == 0){
    return failed("cannot read input file #2");
  }

  Stopwatch watch;
  watch.start();

  ISpellCheck * checker = (ISpellCheck *) createObject("ISpellCheck");
  if(checker == NULL){
    return nullObject("ISpellCheck");
  }

  watch.pause();
  checker->loadDictionary(words);
  watch.unpause();

  for(size_t i = 0; i < commands.size(); ++i){
    SpellCheckCmd cmd = commands[i];
    std::vector<std::string> product_corrections = checker->suggestCorrections(cmd.word);
    watch.pause();
    std::sort(product_corrections.begin(), product_corrections.end());
    if(product_corrections != cmd.corrections){
      return failed("corrections mismatch");
    }
    watch.unpause();
  }

  watch.stop();
  return passed(watch.getTime());
}
TestCase * Grader07::testStringSearch(std::string cmds_filename, std::string input_filename)
{
  std::vector<StringSearchCmd> commands;

  Commands07 cmds07;
  cmds07.loadStringSearchCommmands(cmds_filename, commands);
  std::string to_search = cmds07.readStringFile(input_filename);

  if(commands.size() == 0){
    return failed("cannot read input file #1");
  }

  if(to_search == ""){
    return failed("cannot read input file #2");
  }

  Stopwatch watch;
  watch.start();

  IStringSearch * searcher = (IStringSearch *) createObject("IStringSearch");
  if(searcher == NULL){
    return nullObject("IStringSearch");
  }

  watch.pause();
  searcher->prepareText(to_search);
  watch.unpause();

  for(size_t i = 0; i < commands.size(); ++i){
    StringSearchCmd cmd = commands[i];
    std::vector<int> product_results = searcher->search(cmd.to_find);
    if(product_results.size() != cmd.positions.size()){
      return failed("incorrect return size");
    }
    std::sort(product_results.begin(), product_results.end());
    if(product_results != cmd.positions){
      return failed("at least one incorrect return index");
    }
  }

  watch.stop();
  return passed(watch.getTime());
}
TestCase * Grader07::testCompress(std::string input_filename, std::string output_filename)
{
  Commands07 cmds07;
  std::string input = cmds07.readStringFile(input_filename);

  Stopwatch watch;
  watch.start();

  ICompress * compressor = (ICompress *) createObject("ICompress");
  if(compressor == NULL){
    return nullObject("ICompress");
  }

  std::string output = compressor->compress(input);
  watch.stop();

  cmds07.writeStringFile(output_filename, output);
  return passed(watch.getTime()+output.size());
}
TestCase * Grader07::testStringSort(std::string input_filename)
{
  std::vector<std::string> input;
  std::vector<std::string> output;

  Commands07 cmds07;
  cmds07.readReads(input_filename, input);
  cmds07.readReads(input_filename, output);

  if(input.size() == 0){
    return failed("cannot read input file #1");
  }  
  
  if(output.size() == 0){
    return failed("cannot read input file #2");
  }  

  Stopwatch watch;
  watch.start();

  IStringSort * sorter = (IStringSort *) createObject("IStringSort");
  if(sorter == NULL){
    return nullObject("IStringSort");
  }

  sorter->sort(input);
  watch.stop();
  
  std::sort(output.begin(), output.end());

  if(input.size() != output.size()){
    return failed("incorrect size");
  }
  if(input != output){
    return failed("at least one incorrect string");
  }

  return passed(watch.getTime());
}
TestCase * Grader07::testDecompress(std::string input_filename, std::string output_filename)
{
  Commands07 cmds07;
  std::string input = cmds07.readStringFile(input_filename);
  std::string gold_output = cmds07.readStringFile(output_filename);
  
  Stopwatch watch;
  watch.start();

  ICompress * compressor = (ICompress *) createObject("ICompress");
  if(compressor == NULL){
    return nullObject("ICompress");
  }

  std::string output = compressor->decompress(input);
  watch.stop();

  if(gold_output != output){
    return failed("results do not match");
  }

  return passed(watch.getTime());
}
Example #11
0
int main() {
    for(int n=5; n<=200; n+=5) {
        printf("\n%d iterations\n", n);
        printf("---------------------------------\n");
        int t = 0;
        matrix A = initializeMatrix(n,n);
        Triangles* workers = new Triangles[n];

        Stopwatch timer;
        timer.start();
        for(int x = 0; x<n; x++) {
            workers[x].setParameters(x, n, A);
            if(!workers[x].StartInternalThread()) {
                printf("Err pthread_create for thread %d \n", x+1);
            }
        }

        for(int x=0; x<n; x++) {
            workers[x].WaitForInternalThreadToExit();
            t += workers[x].getResult();
        }
        t /= 3;
        timer.stop();

        float averageTime = [](Triangles* w, int n)->float {
            float sum = 0;
            for(int x = 0; x<n; x++) {
                sum += w[x].getTime();
            }
            return sum/n;
        }(workers, n);

        float maxTime = [](Triangles* w, int n)->float {
            float max = 0;
            for(int x = 0; x<n; x++) {
                if(w[x].getTime() > max) {
                    max = w[x].getTime();
                }
            }
            return max;
        }(workers, n);

        float minTime = [](Triangles* w, int n)->float {
            float min = w[0].getTime();
            for(int x = 1; x<n; x++) {
                if(w[x].getTime() < min) {
                    min = w[x].getTime();
                }
            }
            return min;
        }(workers, n);

        float linearTime = [](Triangles* w, int n)->float {
            float sum = 0;
            for(int x = 0; x<n; x++) {
                sum += w[x].getTime();
            }
            return sum;
        }(workers, n);

        float overallTime = timer.getTime();

        printf("All tasks ended succesfully\n");
        printf("Found %d triangles \n", t);
        printf("Average search time:\t %.0f \n", averageTime);
        printf("Max search time:\t %.0f \n", maxTime);
        printf("Min search time:\t %.0f \n", minTime);
        printf("Linear approximate time: %.0f \n", linearTime);
        printf("Overall search time:\t %.0f\n", overallTime);
        printf("---------------------------------\n");
    }
    getchar();

    return 0;
}
Example #12
0
int main (int argc, const char * argv[]){
 
    
    //Declaring Variables for for loops
    int minIters = 2;
    int maxIters = 32768;
    int minSize = 500;
    int maxSize = 2500;
    int a = 0;
    int b = 0;
    
    cl_platform_id platform;
    cl_device_id device;
    cl_context context;
    cl_command_queue queue;
    cl_program program;
    cl_kernel kernel;
    
    
    //A cl_int used to store error flags that are returned if OpenCL function does not execute properly
    cl_int err;
    const char* fileName;
    const char* kernelName;
    
    FILE *program_handle;
    char *program_buffer, *program_log;
    size_t program_size, log_size;
    std::string programLog;
    
    //The number of work items in each dimension of the data.
    size_t work_units_per_kernel;
    
    Stopwatch sw;
    
    
    //Outer most loop: This loop should encompass all code and is used in order to loop over
    //different values of the iterations and array size to create the data for the plot.
    
    for(int i = minSize; i < maxSize; i+=100){
        std::cout << "Array Size: " << i << std::endl;
        for(int j = minIters; j < maxIters; j*=2){
            std::cout << "Iterations: " << j << std::endl;
            
            //TODO: Move lower in the code
            //data[a][b] = datagpu.runGPUBenchmark(10, 3, 3);
            
            //Initializing the arrays
            
            int n1 = i;
            int n2 = i+1;
            int iters = j;
            long dims = n1*n2;
            
            float **h_xx = new float*[n1];
            float **h_yy = new float*[n1];
            float **h_zz = new float*[n1];
            
            for(int x = 0; x<n1; x++){
                
                h_xx[x] = new float [n2];
                h_yy[x] = new float [n2];
                h_zz[x] = new float [n2];
                
                //Initializing the arrays.
                for(int y = 0; y<n2; y++){

                    h_xx[x][y] = x+y;
                    h_yy[x][y] = x+y;
                    
                }
                
            }
            
            //Here the benchmark occurs. Within this while loop must occurr all OpenCL calls and executions
            int maxTime = 5;
            int count = 0;
            sw.restart();
            while (sw.getTime() < maxTime){
                
                err = clGetPlatformIDs(1, &platform, NULL);
                if (err != CL_SUCCESS){
                    std::cout << "Error: Failed to locate the platform." << std::endl;
                    exit(1);
                }
                err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL);
                if(err != CL_SUCCESS){
                    std::cout << "Error: Failed to locate the device." << std::endl;
                    exit(1);
                    
                }
                context = clCreateContext(NULL, 1, &device, NULL, NULL, &err);
                if(err != CL_SUCCESS){
                    std::cout << "Error: Could not create a context." << std::endl;
                    exit(1);
                }

                
                program_handle = fopen("floptmem.cl", "r");
                if(!program_handle){
                    std::cout << "Error: Failed to load Kernel" << std::endl;
                    exit(1);
                }
                fseek(program_handle, 0, SEEK_END);
                program_size = ftell(program_handle);
                rewind(program_handle);
                program_buffer = (char*)malloc(program_size + 1);
                program_buffer[program_size] = '\0';
                fread(program_buffer, sizeof(char), program_size, program_handle);
                fclose(program_handle);
                
                program = clCreateProgramWithSource(context, 1, (const char **)&program_buffer, (const size_t *)&program_size, &err);
                if(err != CL_SUCCESS){
                    std::cout << "Error: Could not create the program" << std::endl;
                    exit(1);
                }
            
                err = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
                if(err != CL_SUCCESS){
                    std::cout << "Error: Could not compile the program" << std::endl;
                    clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size);
                    program_log = (char*)malloc(log_size+1);
                    program_log[log_size] = '\0';
                    clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, log_size+1, program_log, NULL);
                    programLog = program_log;
                    std::cout << programLog << std::endl;
                    free(program_log);
                    exit(1);
                }
                
                kernel = clCreateKernel(program, "arraysum", &err);
                if(err != CL_SUCCESS){
                    std::cout << "Error: Could not create the kernel." << std::endl;
                    exit(1);
                }
                
                queue = clCreateCommandQueue(context, device, 0, &err);
                if(err != CL_SUCCESS){
                    std::cout << "Error: Could not create the queue." << std::endl;
                    exit(1);
                }
                
                cl_mem d_xx, d_yy, d_zz;
                
                d_xx = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float)*dims, NULL, &err);
                if(err != CL_SUCCESS){
                    std::cout << "Error: Could not create the buffer." << std::endl;
                    exit(1);
                }

                d_yy = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float)*dims, NULL, &err);
                if(err != CL_SUCCESS){
                    std::cout << "Error: Could not create the buffer." << std::endl;
                    exit(1);
                }

                d_zz = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float)*dims, NULL, &err);
                if(err != CL_SUCCESS){
                    std::cout << "Error: Could not create the buffer." << std::endl;
                    exit(1);
                }
                
                float *h_xx1 = new float[dims];
                float *h_yy1 = new float[dims];
                float *h_zz1 = new float[dims];
                
                
                //packing arrays
                int k = 0;
                for (int x = 0; x < n1; x++){
                    for (int y = 0; y < n2; y++){
                        h_xx1[k] = h_xx[x][y];
                        h_yy1[k] = h_yy[x][y];
                        k++;
                    }
                    
                }
            
                err = clEnqueueWriteBuffer(queue, d_xx, CL_FALSE, 0, sizeof(float)*dims, h_xx1, 0, NULL, NULL);
                if(err != CL_SUCCESS){
                    std::cout << "Error: Could not write to buffer." << std::endl;
                    exit(1);
                }
                err = clEnqueueWriteBuffer(queue, d_yy, CL_FALSE, 0, sizeof(float)*dims, h_yy1, 0, NULL, NULL);
                if(err != CL_SUCCESS){
                    std::cout << "Error: Could not write to buffer." << std::endl;
                    exit(1);
                }
                
                
                err = clSetKernelArg(kernel, 0, sizeof(cl_mem), &d_xx);
                if(err != CL_SUCCESS){
                    std::cout << "Error: Could not set the kernel argument." << std::endl;
                    std::cout << "OpenCL error code: " << err << std::endl;
                    exit(1);
                }
                
                
                err = clSetKernelArg(kernel, 1, sizeof(cl_mem), &d_yy);
                if(err != CL_SUCCESS){
                    std::cout << "Error: Could not set the kernel argument." << std::endl;
                    std::cout << "OpenCL error code: " << err << std::endl;
                    exit(1);
                }
                
                err = clSetKernelArg(kernel, 2, sizeof(cl_mem), &d_zz);
                if(err != CL_SUCCESS){
                    std::cout << "Error: Could not set the kernel argument." << std::endl;
                    std::cout << "OpenCL error code: " << err << std::endl;
                    exit(1);
                }
                
                err = clSetKernelArg(kernel, 3, sizeof(j), &j);
                if(err != CL_SUCCESS){
                    std::cout << "Error: Could not set the integer kernel argument." << std::endl;
                    std::cout << "OpenCL error code: " << err << std::endl;
                    exit(1);
                }
                
                
                work_units_per_kernel = dims;
                err = clEnqueueNDRangeKernel(queue, kernel, 1, NULL, &work_units_per_kernel, NULL, 0, NULL, NULL);
                if(err != CL_SUCCESS){
                    std::cout << "Error: Could not execute the kernel." << std::endl;
                    exit(1);
                }

    
                
                err = clEnqueueReadBuffer(queue, d_zz, CL_TRUE, 0, sizeof(float)*dims, h_zz1, 0, NULL, NULL);
                if(err != CL_SUCCESS){
                    std::cout << "Error: Could not read data from the kernel." << std::endl;
                    std::cout << "OpenCL error code: " << std::endl;
                    exit(1);
                }
                
                //unpacking the 1D array
                k = 0;
                for (int x = 0; x < n1; x++){
                    for (int y = 0; y < n2; y++){
                        h_zz[x][y] = h_zz1[k];
                        k++;
                    }
                }
                
                delete [] h_xx1;
                delete [] h_yy1;
                delete [] h_zz1;
      
            	count++;

                //Freeing up memory. Hopefully!
                clReleaseMemObject(d_xx);
                clReleaseMemObject(d_yy);
                clReleaseMemObject(d_zz);
                clReleaseKernel(kernel);
                clReleaseCommandQueue(queue);
                clReleaseProgram(program);
                clReleaseContext(context);
                

            }

            sw.stop();

            for (int x = 0; x < n1; x++)
			{
                delete [] h_xx[x];
                delete [] h_yy[x];
                delete [] h_zz[x];
            }
            
            delete [] h_xx;
            delete [] h_yy;
            delete [] h_zz;
            

            
            float n1f = (float) n1;
            float n2f = (float) n2;
            float countf = (float) count;

			
			std::cout << "n1: " << n1f << std::endl;
			std::cout << "n2: " << n2f << std::endl;
			std::cout << "Iters: " << iters << std::endl;
			std::cout << "count: " << countf << std::endl;
			std::cout << "Time: " << sw.getTime() << std::endl;
			std::cout << std::endl;
            
            float mflops = n1f*n2f*countf*iters*1.0e-06/sw.getTime();
            
            //std::cout << "Number of MegaFLOPs: " << n1f*n2f*500*countf*1.0e-6 << std::endl;
            std::cout << mflops << " MegaFLOPS" << std::endl;

            b++;
        }
        a++;
        std::cout << std::endl;
    }
    
    
    return 0;
}
TestCase * Grader02::testWorkload4(int len, int order, int merge_count,
	int merge_len){

	std::vector<int> input;
	std::vector<int> sorted;
	createVector(input, sorted, order, len, false);

	Stopwatch watch;
	watch.start();

	IPriorityQueue * queue = (IPriorityQueue *)createObject("IPriorityQueue4");
	if (queue == NULL){
		return nullObject("IPriorityQueue4");
	}

	watch.pause();
	GoldPriorityQueue gold_queue(sorted);

	for (size_t i = 0; i < merge_len; ++i){
		int key = input[i];
		std::string value = randomValue();
		gold_queue.push_back(key, value);

		watch.unpause();
		IKeyValue * key_value = (IKeyValue *)createObject("IKeyValue4");
		if (key_value == NULL){
			return nullObject("IKeyValue4");
		}

		key_value->setKey(key);
		key_value->setValue(value);

		queue->enqueue(key_value);

		int size = queue->size();
		if (size != gold_queue.size()){
			return failed("after enqueue, size is incorrect");
		}

		int user_key = queue->lowestKey();
		IVectorString * user_values = queue->lowestValues();
		gold_queue.iterate();
		int gold_key = gold_queue.lowestKey();
		std::vector<std::string> values = gold_queue.getValues(gold_key);
		watch.pause();

		if (gold_key != user_key){
			return failed("after enqueue, lowest key is incorrect");
		}

		if (valuesEqual(user_values, values) == false){
			return failed("after enqueue, values incorrect");
		}
	}

	for (int i = 1; i < merge_count; ++i){
		watch.unpause();
		IPriorityQueue * queue2 = (IPriorityQueue *)createObject("IPriorityQueue4");
		if (queue == NULL){
			return nullObject("IPriorityQueue4");
		}

		watch.pause();

		for (int j = (i * merge_len); j < ((i + 1) * merge_len); ++j){
			int key = input[j];
			std::string value = randomValue();
			gold_queue.push_back(key, value);

			watch.unpause();
			IKeyValue * key_value = (IKeyValue *)createObject("IKeyValue4");
			if (key_value == NULL){
				return nullObject("IKeyValue4");
			}

			key_value->setKey(key);
			key_value->setValue(value);

			queue2->enqueue(key_value);
			watch.pause();
		}

		watch.unpause();
		queue->merge(queue2);
		watch.pause();

		gold_queue.iterate();

		watch.unpause();
		int user_key = queue->lowestKey();
		IVectorString * user_values = queue->lowestValues();
		watch.pause();

		int gold_key = gold_queue.lowestKey();
		std::vector<std::string> values = gold_queue.getValues(gold_key);

		if (gold_key != user_key){
			return failed("during dequeue, lowest key is incorrect");
		}

		if (valuesEqual(user_values, values) == false){
			return failed("during dequeue, values incorrect");
		}
	}

	return passed(watch.getTime());
}
Example #14
0
int main(void)
{
  //std::cout << "Generating a time series on device "<< tim.get_nsamps() << std::endl;
  //DeviceTimeSeries<float> d_tim(8388608);
  //d_tim.set_tsamp(0.000064);
  TimeSeries<float> tim;
  tim.from_file("/lustre/home/ebarr/Soft/peasoup/tmp5.tim");
  DeviceTimeSeries<float> d_tim(tim);
  
  unsigned int size = d_tim.get_nsamps();
  
  TimeSeriesFolder folder(size);
  
  //DeviceTimeSeries<float> d_tim_r(fft_size); //<----for resampled data
  //TimeDomainResampler resampler;
  

  float* folded_buffer;
  cudaError_t error;
  cufftResult result;
  error = cudaMalloc((void**)&folded_buffer, sizeof(float)*size);
  ErrorChecker::check_cuda_error(error);


  unsigned nints = 64;
  unsigned nbins = 32;

  cufftComplex* fft_out;
  error = cudaMalloc((void**)&fft_out, sizeof(cufftComplex)*nints*nbins);
  cufftHandle plan;
  result = cufftPlan1d(&plan,nbins,CUFFT_R2C, nints);
  ErrorChecker::check_cufft_error(result);
  Stopwatch timer;

  FoldedSubints<float> folded_array(nbins,nints);
  //folder.fold(d_tim,folded_array,0.007453079228);

  std::cout << "made it here" << std::endl;
  

  FoldOptimiser optimiser(nbins,nints);
  timer.start();
  for (int ii=0;ii<1;ii++){
    //FoldedSubints<float> folded_array(nbins,nints);
    folder.fold(d_tim,folded_array,0.007453099228);
    Utils::dump_device_buffer<float>(folded_array.get_data(),nints*nbins,"original_fold.bin");
    
    optimiser.optimise(folded_array);
  }
  timer.stop();
  
  /*
  float* temp = new float [nints*nbins];
  
  cudaMemcpy(temp,folded_buffer,nints*nbins*sizeof(float),cudaMemcpyDeviceToHost);
  ErrorChecker::check_cuda_error();

  for (int ii=0;ii<nints*nbins;ii++)
    std::cout << temp[ii] << std::endl;
  */

  
  std::cout << "Total execution time (s): " << timer.getTime()<<std::endl;
  std::cout << "Average execution time (s): " << timer.getTime()/1000.0 << std::endl;



  return 0;
}
Example #15
0
int
FileChunk::assemble(synergy::IStream* stream, String& dataReceived, size_t& expectedSize)
{
	// parse
	UInt8 mark = 0;
	String content;
	static size_t receivedDataSize;
	static double elapsedTime;
	static Stopwatch stopwatch;

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

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

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

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

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

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

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

	return kError;
}
Example #16
0
void
StreamChunker::sendClipboard(
				String& data,
				size_t size,
				ClipboardID id,
				UInt32 sequence,
				IEventQueue* events,
				void* eventTarget)
{
	s_isChunkingClipboard = true;
	
	// send first message (data size)
	String dataSize = synergy::string::sizeTypeToString(size);
	ClipboardChunk* sizeMessage = ClipboardChunk::start(id, sequence, dataSize);
	
	events->addEvent(Event(events->forClipboard().clipboardSending(), eventTarget, sizeMessage));

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

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

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

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

			sendStopwatch.reset();
		}
	}

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

	events->addEvent(Event(events->forClipboard().clipboardSending(), eventTarget, end));
	
	s_isChunkingClipboard = false;
}
Example #17
0
void
StreamChunker::sendFile(
				char* filename,
				IEventQueue* events,
				void* eventTarget)
{
	s_isChunkingFile = true;
	
	std::fstream file(reinterpret_cast<char*>(filename), std::ios::in | std::ios::binary);

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

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

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

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

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

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

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

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

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

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

			if (sentLength == size) {
				break;
			}

			sendStopwatch.reset();
		}
	}

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

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

	file.close();
	
	s_isChunkingFile = false;
}
TestCase * Grader02::testWorkload1(int len, int order){

	std::vector<int> input;
	std::vector<int> sorted;
	createVector(input, sorted, order, len, true);

	Stopwatch watch;
	watch.start();

	IPriorityQueue * queue = (IPriorityQueue *)createObject("IPriorityQueue1");
	if (queue == NULL){
		return nullObject("IPriorityQueue1");
	}

	watch.pause();
	GoldPriorityQueue gold_queue(sorted);
	for (size_t i = 0; i < input.size(); ++i){
		int key = input[i];
		std::string value = randomValue();
		gold_queue.push_back(key, value);

		watch.unpause();
		IKeyValue * key_value = (IKeyValue *)createObject("IKeyValue1");
		if (key_value == NULL){
			return nullObject("IKeyValue1");
		}

		key_value->setKey(key);
		key_value->setValue(value);

		queue->enqueue(key_value);

		int size = queue->size();
		if (size != gold_queue.size()){
			return failed("after enqueue, size is incorrect");
		}

		int user_key = queue->lowestKey();
		IVectorString * user_values = queue->lowestValues();
		gold_queue.iterate();
		int gold_key = gold_queue.lowestKey();
		std::vector<std::string> values = gold_queue.getValues(gold_key);
		watch.pause();

		if (gold_key != user_key){
			return failed("after enqueue, lowest key is incorrect");
		}

		if (valuesEqual(user_values, values) == false){
			return failed("after enqueue, values incorrect");
		}

		bool check_sort = true;
		if (len != 10 && i % 100 != 0){
			check_sort = false;
		}

		if (check_sort){
			watch.unpause();
			IVectorKeyValue * user_sorted = queue->returnSorted();
			watch.pause();
			if (sortedEqual(user_sorted, gold_queue.returnSorted()) == false){
				return failed("after enqueue, sorted is not equal");
			}
		}
	}

	gold_queue.iterate();
	int count = 0;
	while (gold_queue.hasNext()){
		watch.unpause();
		int user_key = queue->lowestKey();
		IVectorString * user_values = queue->lowestValues();
		watch.pause();

		int gold_key = gold_queue.lowestKey();
		std::vector<std::string> values = gold_queue.getValues(gold_key);

		if (gold_key != user_key){
			return failed("during dequeue, lowest key is incorrect");
		}

		if (valuesEqual(user_values, values) == false){
			return failed("during dequeue, values incorrect");
		}

		watch.unpause();
		int size = queue->size();
		watch.pause();
		if (size != gold_queue.size()){
			return failed("during dequeue, size is incorrect");
		}

		bool check_sort = true;
		if (len != 10 && count % 100 != 0){
			check_sort = false;
		}

		if (check_sort){
			IVectorKeyValue * user_sorted = queue->returnSorted();
			std::vector<std::pair<int, std::string> > gold_sorted = gold_queue.returnSorted();
			if (sortedEqual(user_sorted, gold_sorted) == false){
				return failed("during dequeue, sorted is not equal");
			}
		}

		watch.unpause();
		queue->dequeue();
		watch.pause();
		gold_queue.dequeue();
		++count;
	}

	return passed(watch.getTime());
}