Lecture 3 - Measuring Runtime and Pseudocode
void f(int *out, const int *in, int size) {
int product = 1;
for (int i = 0; i < size; i++) {
product *= in[i]; // multiplication
}
for (int i = 0; i < size; i++) {
out[i] = product / in[i];
}
} // f()
Measuring Runtime on Linux - produce a runtime report with this command, if you're in the current folder
(the % just means you're in the terminal, though usually it's $?)
% /usr/bin/time ./progName -options args
Kill it with control-C
Measuring Time in C++
ru_utime This is the total amount of time spent executing in user mode, expressed in a timeval structure (seconds plus microseconds).
user mode cannot see all of memory, it cannot communicate with I/O devices, and can only really do number-crunching
the
ru_utime
struct returns the amount of time your program has spent doing actual computation
ru_stime This is the total amount of time spent executing in kernel mode, expressed in a timeval structure (seconds plus microseconds).
- kernel can do: memory page allocation, filesystem read/write, printing things to the screen, etc.
- the
ru_stime
struct returns the amount of time your program has been waiting for an answer from the kernel when doing disk access, printing to the screen etc
#include <iostream>
#include <sys/resource.h>
#include <sys/time.h>
class Timer {
private:
struct rusage startu;
struct rusage endu;
double duration;
public:
Timer() {getrusage(RUSAGE_SELF, &startu); }
void recordTime() {
getrusage(RUSAGE_SELF, &endu);
double start_sec = startu.ru_utime.tv_sec + startu.ru_utime.tv_usec/1e7;
double end_sec = end.ru_utime.tv_sec + endu.ru_utime.tv_usec/1e7;
duration = end_sec - start_sec; // get duration for elapsed time
} // recordTime()
double getTime() { return duration; }
}; // Timer
Pseudocode
Algorithm arrayMax(A, n)
Input array A of n integers
Output max element of A
current Max = A[0]
for i = 1 to n - 1
if A[i] > currentMax
currentMax = A[i]
return currentMax # can also return multiple items in pseudocode
C++ Code
int arrayMax(int A[], int n) {
int currentMax = A[0];
for (int i = 1; i < n; ++i) {
if (currentMax < A[i]) currentMax = A[i];
}
return currentMax;
} // arrayMax()
Exam Prep - Binomial Coefficient
(n, k) = (n-1, k-1) + (n-1, k) with all (n, 0) and (n, n) having a value of 1.
Tail-Recursive Solution (might be buggy)
double bin_coef_rekt(double n, double k) {
if (n < 0 || k < 0) return 0;
if (n == k ||k == 0) return 1;
else if (n == 0 && k > 0) return 0;
return bin_coef_iter(n - 1, k - 1) + bin_coef_iter(n - 1, k);
}