Home CPSC 425

Lab 2: Thread Timing

 

Objective

To get more experience with pthreads, and also to use timing functions in C.


 

Task

An important part of parallel programming is load balancing. Ideally, each thread will spend the same amount of time working as each of the others. For this lab, you will analyze the load balance between the threads of the π estimation program.

To do this, simply have each thread time the amount of time it takes to execute. In order to figure out how long a thread takes, we will need to get the time at two points, once at the start of the thread and once at the end. Then we can subtract the two values to find the elapsed time.

The time() function unfortunately has only second resolution. In order to have more accurate numbers, we will find the number milliseconds since the epoch, which is January 1st, 1970.

To do this, first include the header file <sys/time.h>. Next create an object of type struct timeval:


struct timeval current;

Then pass this object into the function gettimeofday:


gettimeofday(&current, NULL);

The second parameter is for passing time zone information, and should be NULL.

The timeval structure contains two fields, tv_sec and tv_usec which contain the number of seconds and microseconds respectively.

To get the number of milliseconds, we can use the following:


unsigned long ms = (current.tv_sec * 1000) + (current.tv_usec / 1000);


 

Details

  1. You should start with your version of the π estimate program.
  2. Add code to the start of the thread function to find the starting time, and code at the end of the function to find the ending time.
  3. Have each thread then print out the elapsed time it took to execute before returning.
  4. Try running the program and see how changing the number of threads affects the balance of time, answering the following questions:
    1. What happens to the balance as you increase from 2 to 4 to 8 threads?
    2. What happens if you use more threads than processors (eg 64)?

 

Submitting

When you're finished, submit both the source code and the analysis (in a text document of some kind, or as a comment) to Canvas.

Copyright © 2024 Ian Finlayson | Licensed under a Creative Commons BY-NC-SA 4.0 License.