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 $\pi$ 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 we have seen 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 $\pi$ estimate program.
  2. Add code to the thread function so that each thread calculates how many milliseconds it took to execute.
  3. Have each thread print out the 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 your program works, email the source code and the analysis to ifinlay@umw.edu.

Copyright © 2018 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.