Emergency sync

This commit is contained in:
Ziad Arafat committed 2023-12-05 20:11:11 -07:00
1 parent 12e2fb1ef8
commit 81fc0cc85a
26 files changed
+2274

No files matched your search

View File
Whitespace-only changes.
+18
View File
@@ -0,0 +1,18 @@
all: count_threes
count_threes: count_threes.c
gcc -fopenmp -o count_threes count_threes.c
run:
for threads in 1 2 4 8 16 32 64; do \
echo "$$threads threads" >> results.txt; \
for i in {1..5}; do \
OMP_NUM_THREADS=$$threads ./count_threes 10000 >> results.txt; \
done; \
done
clean:
rm -f count_threes results.txt
Binary file not shown.
+72
View File
@@ -0,0 +1,72 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <omp.h>
/**
* @brief Function to count the number of threes in an array using OpenMP
* @param array The array to be counted
* @param length The length of the array to be counted
* @return int The number of threes in the array
*/
int count3s(int* array, int length)
{
int count = 0;
int i;
#pragma omp parallel for reduction(+:count)
for (i = 0; i < length; i++) {
if (array[i] == 3) {
count++;
}
}
return count;
}
/**
* @brief Function to generate a random array to test our count3s function
* @param size The size of the array to be generated
* @return int* The pointer to the array
*/
int* generate_array(int size) {
int* array = (int*) malloc(size * sizeof(int));
srand(time(NULL));
for (int i = 0; i < size; i++) {
array[i] = rand() % 3 + 1;
}
return array;
}
int main(int argc, char const *argv[])
{
// parse arguments
if (argc != 2) {
printf("Usage: %s <array_size>\n", argv[0]);
return 1;
}
int length = atoi(argv[1]);
if (length <= 0) {
printf("Error: array size must be a positive integer\n");
return 1;
}
// generate array
int* array = generate_array(length);
// run the function and record running time
double start_time, end_time;
start_time = omp_get_wtime();
int count = count3s(array, length);
end_time = omp_get_wtime();
printf("count: %d, ", count);
printf("Time taken: %f\n", end_time - start_time);
free(array);
return 0;
}
@@ -0,0 +1,261 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Times for 1 thread: [1.503683, 1.503534, 1.504619, 1.504074, 1.504186]\n",
"Times for 2 threads: [0.753239, 0.761634, 0.752398, 0.754443, 0.752339]\n",
"Times for 4 threads: [0.432492, 0.380995, 0.684529, 0.43349, 0.427252]\n",
"Times for 8 threads: [0.238623, 0.24504, 0.241586, 0.240508, 0.189636]\n",
"Times for 16 threads: [0.09745, 0.096661, 0.128006, 0.125363, 0.125371]\n",
"Times for 32 threads: [0.08041, 0.069265, 0.078767, 0.069674, 0.086196]\n",
"Times for 64 threads: [0.085384, 0.087096, 0.064716, 0.061082, 0.062371]\n"
]
}
],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
" # Provided program output as a string\n",
"program_output = \"\"\"\n",
"1 threads\n",
"count: 99991099\n",
"Time taken: 1.503683 seconds\n",
"count: 99995163\n",
"Time taken: 1.503534 seconds\n",
"count: 99995800\n",
"Time taken: 1.504619 seconds\n",
"count: 99978792\n",
"Time taken: 1.504074 seconds\n",
"count: 100003511\n",
"Time taken: 1.504186 seconds\n",
"2 threads\n",
"count: 100014341\n",
"Time taken: 0.753239 seconds\n",
"count: 100001384\n",
"Time taken: 0.761634 seconds\n",
"count: 99994972\n",
"Time taken: 0.752398 seconds\n",
"count: 99980303\n",
"Time taken: 0.754443 seconds\n",
"count: 100003100\n",
"Time taken: 0.752339 seconds\n",
"4 threads\n",
"count: 99997517\n",
"Time taken: 0.432492 seconds\n",
"count: 100002006\n",
"Time taken: 0.380995 seconds\n",
"count: 100013130\n",
"Time taken: 0.684529 seconds\n",
"count: 100001312\n",
"Time taken: 0.433490 seconds\n",
"count: 99992179\n",
"Time taken: 0.427252 seconds\n",
"8 threads\n",
"count: 99990805\n",
"Time taken: 0.238623 seconds\n",
"count: 100001043\n",
"Time taken: 0.245040 seconds\n",
"count: 100005162\n",
"Time taken: 0.241586 seconds\n",
"count: 100011768\n",
"Time taken: 0.240508 seconds\n",
"count: 49995496\n",
"Time taken: 0.189636 seconds\n",
"16 threads\n",
"count: 37498358\n",
"Time taken: 0.097450 seconds\n",
"count: 31255893\n",
"Time taken: 0.096661 seconds\n",
"count: 81246280\n",
"Time taken: 0.128006 seconds\n",
"count: 93751286\n",
"Time taken: 0.125363 seconds\n",
"count: 87496828\n",
"Time taken: 0.125371 seconds\n",
"32 threads\n",
"count: 100003281\n",
"Time taken: 0.080410 seconds\n",
"count: 21877522\n",
"Time taken: 0.069265 seconds\n",
"count: 87495971\n",
"Time taken: 0.078767 seconds\n",
"count: 75019297\n",
"Time taken: 0.069674 seconds\n",
"count: 96885388\n",
"Time taken: 0.086196 seconds\n",
"64 threads\n",
"count: 71864758\n",
"Time taken: 0.085384 seconds\n",
"count: 82811032\n",
"Time taken: 0.087096 seconds\n",
"count: 84369914\n",
"Time taken: 0.064716 seconds\n",
"count: 76551863\n",
"Time taken: 0.061082 seconds\n",
"count: 84397515\n",
"Time taken: 0.062371 seconds\n",
"\"\"\"\n",
"\n",
"# Split the output into lines\n",
"lines = program_output.strip().split(\"\\n\")\n",
"\n",
"# Initialize lists to hold the times for each thread count\n",
"times_1_thread = []\n",
"times_2_threads = []\n",
"times_4_threads = []\n",
"times_8_threads = []\n",
"times_16_threads = []\n",
"times_32_threads = []\n",
"times_64_threads = []\n",
"\n",
"# Initialize a list of lists to make it easier to append in a loop\n",
"all_times = [\n",
" times_1_thread,\n",
" times_2_threads,\n",
" times_4_threads,\n",
" times_8_threads,\n",
" times_16_threads,\n",
" times_32_threads,\n",
" times_64_threads,\n",
"]\n",
"\n",
"# Current thread count index\n",
"thread_count_index = 0\n",
"\n",
"# Parse the output and fill the lists\n",
"for line in lines:\n",
" if \"Time taken:\" in line:\n",
" # Extract the time taken from the line\n",
" time_taken = float(line.split()[-2])\n",
" # Append the time to the appropriate list\n",
" all_times[thread_count_index].append(time_taken)\n",
" # Check if the current thread count's list is filled with 5 runs\n",
" if len(all_times[thread_count_index]) == 5:\n",
" # Move to the next thread count\n",
" thread_count_index += 1\n",
"\n",
"# Now all_times contains the lists of times for each thread count\n",
"print(\"Times for 1 thread:\", times_1_thread)\n",
"print(\"Times for 2 threads:\", times_2_threads)\n",
"print(\"Times for 4 threads:\", times_4_threads)\n",
"print(\"Times for 8 threads:\", times_8_threads)\n",
"print(\"Times for 16 threads:\", times_16_threads)\n",
"print(\"Times for 32 threads:\", times_32_threads)\n",
"print(\"Times for 64 threads:\", times_64_threads)\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAmUAAAJwCAYAAADIlBYPAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/SrBM8AAAACXBIWXMAAA9hAAAPYQGoP6dpAABmvklEQVR4nO3dd3hTZf/H8c9J0qYtpaXsVbZSloCgCCiIIBURJ4qiMlzog4KgPIoLJ0OZ+qAoKjhAcYETFBFQXPzYqICykT27gI7k/P4oSRuatik0Tdq8X9fVS3JyTs43aYVP7/s+32OYpmkKAAAAAWUJdAEAAAAglAEAAAQFQhkAAEAQIJQBAAAEAUIZAABAECCUAQAABAFCGQAAQBAglAEAAAQBQhkAAEAQIJQBIWLJkiUyDENLliwJdCluhmHo/vvvD3QZkqTt27fLMAyNHz8+0KX45NJLL9Wll14a6DIC7j//+Y8uv/zyQJdR5t1888266aabAl1GmUcoQ5G9+uqrMgxD7dq1C3Qp8OLVV1/VzJkzA11GUKhXr54Mwyj0q6x/Xg6HQzNmzNCll16qihUrym63q169eho4cKBWrFgR6PIkSX/99Zeefvppbd++3edjtm3bpjfffFOPPfZYnucOHz6sESNGqHHjxoqIiFDFihWVmJior776qhirLh6un9Nu3bp5fX769Onun9Xc36+nn37a4+c4KipKTZs21RNPPKHk5GSfzp2cnKxnnnlGLVu2VHR0tCIjI9W8eXM98sgj2rNnj3u/Rx55RJ9++qnWrl17dm8WBbIFugCUPrNmzVK9evW0fPlybd68WY0aNQp0Scjl1VdfVeXKlTVgwACP7Z06ddKJEycUHh4emMICYPLkyUpNTX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rp0iIyPVuHFjff/993lqLY7Pa9asWe5ppjZt2ujHH390P7d48WIZhqG5c+fmOW727NkyDEO//vprkc5XmDfeeEMNGzaU3W7XBRdcoP/7v//zeH7AgAGKjo7Wli1bdOWVV6p8+fK69dZbJUlOp1OTJ09Ws2bNFBERoWrVqmnQoEE6evSox2t8/vnn6tmzp2rWrCm73a6GDRvqueeek8PhyLeeyMhIXXjhhfrpp598eh///vuvXn/9dV1++eV68MEH8zxvtVr18MMPe4ySrV69Wj169FBMTIyio6PVtWtX/fbbbx7HuabNTuf6Oc09BVmvXj1dddVVWrZsmS688EJFRESoQYMGHqMtM2fO1I033ihJ6tKli/tnt6D1j8uWLdOhQ4fyTPl9+umn+uOPP/Too4/mWWJhtVr1+uuvq0KFCh7/37n+35gzZ44ee+wxVa9eXeXKldPVV1+tXbt25Tn377//riuuuEKxsbGKiopS586d9fPPP3v9jDZv3qwBAwaoQoUKio2N1cCBA3X8+PE8rxkREaHrr79es2fP9tj+wQcfKC4uTomJifl+Fqe77LLLJGVP7+bHNRX5+OOP6+KLL87zfExMjF544QWPbZdffrnS0tK0cOFCn2tB0RDKUCSzZs3S9ddfr/DwcN1yyy36559/3P9ghYWF6brrrtO8efOUkZHhcdy8efOUnp6um2++WVL2P1xXX321xo8fr169eumVV17Rtddeq0mTJqlPnz55zvvDDz9o2LBh6tOnj6ZMmeKe3pgyZYpat26tZ599VqNHj5bNZtONN96or7/+2uP4AQMG6JVXXtGVV16pcePGKTIyUj179sxznv379+uiiy7S999/r/vvv19TpkxRo0aNdOedd2ry5Mln/LkdPnxYPXr0UKtWrTR58uQ80y2+euCBB7R27VqNGjVK9913n7788kuPhfKTJ09W7dq1lZCQoPfee0/vvfeeHn/88QJf8+jRo7rqqqvUrl07vfjii7Lb7br55ps1Z84c3Xzzzbryyis1duxYpaWlqXfv3kpJSXEfWxyf19KlS/Xggw/qtttu07PPPqvDhw/riiuu0B9//CEpOzjGx8d7/ALgMmvWLDVs2FDt27f36Vy+mD17tl566SUNGjRIzz//vLZv367rr79emZmZHvtlZWUpMTFRVatW1fjx43XDDTdIkgYNGqQRI0aoY8eOmjJligYOHKhZs2YpMTHR4zVmzpyp6OhoDR8+XFOmTFGbNm301FNP6dFHH/U4z1tvvaVBgwapevXqevHFF9WxY8d8w8Lp5s+fr6ysLN1+++0+vfc///xTl1xyidauXav//ve/evLJJ7Vt2zZdeuml+v333316DW82b96s3r176/LLL9eECRMUFxenAQMG6M8//5SUPbU+ZMgQSdJjjz3m/tlt0qRJvq/5yy+/yDAMtW7d2mP7l19+KUnq16+f1+NiY2N1zTXXaOPGjdq8ebPHcy+88IK+/vprPfLIIxoyZIgWLlyobt266cSJE+59fvjhB3Xq1EnJyckaNWqURo8erWPHjumyyy7T8uXL85zvpptuUkpKisaMGaObbrpJM2fO1DPPPOO1tr59+2r58uXasmWLe9vs2bPVu3dvhYWF5ftZnM51fKVKlfLd54svvpAkn382JKlp06aKjIzME0BRjAI9VIfSY8WKFaYkc+HChaZpmqbT6TRr165tDh061L3Pt99+a0oyv/zyS49jr7zySrNBgwbux++9955psVjyDJtPmzbNlGT+/PPP7m2STIvFYv755595ajp+/LjHY9fUxWWXXebetnLlSlOS+eCDD3rsO2DAAFOSOWrUKPe2O++806xRo4Z56NAhj31vvvlmMzY2Ns/5fNG5c2dTkjlt2rQ8z51+fpe6deua/fv3dz+eMWOGKcns1q2b6XQ63duHDRtmWq1W89ixY+5t+U1fLl68OM/0kKu22bNnu7dt3LjR/Znnnv5xfW9nzJjh3na2n5ckU5K5YsUK97YdO3aYERER5nXXXefeNnLkSNNut3u8zwMHDpg2m83r55cfX6YvK1WqZB45csS9/fPPP8/zM92/f39Tkvnoo496vMZPP/1kSjJnzZrlsX3BggV5tnv7bAYNGmRGRUWZJ0+eNE0z++e5atWqZqtWrcz09HT3fm+88YYpqdDpy2HDhpmSzNWrVxe4n8u1115rhoeHm1u2bHFv27Nnj1m+fHmzU6dO7m2uabPTuX5Oc3++devWNSWZP/74o3vbgQMHTLvdbj700EPubUWdvrztttvMSpUq5dneqlUrMzY2tsBjJ06caEoyv/jiC9M0c/7fqFWrlpmcnOze76OPPjIlmVOmTDFNM/vvvHPOOcdMTEz0+P/w+PHjZv369c3LL7/cvc31Gd1xxx0e577uuuvy1F23bl2zZ8+eZlZWllm9enXzueeeM03TNP/66y9Tkrl06VL3Z+tt+nLTpk3mwYMHzW3btpmvv/66abfbzWrVqhW4TKJ169aFfk7enHvuuWaPHj2KfBx8w0gZfDZr1ixVq1bNPcpjGIb69OmjDz/80D3lctlll6ly5cqaM2eO+7ijR49q4cKFHiNgH3/8sZo0aaKEhAQdOnTI/eUadl+8eLHHuTt37qymTZvmqSkyMtLjPElJSbrkkku0atUq93bXVOd//vMfj2MfeOABj8emaerTTz9Vr169ZJqmR12JiYlKSkryeN2isNvtXqd1i+qee+7xmDa65JJL5HA4tGPHjjN+zejoaPcIpiQ1btxYFSpUUJMmTTymf1x/3rp1q6Ti+7zat2+vNm3auB/XqVNH11xzjb799lv3z1W/fv2Unp7uMTU9Z84cZWVl6bbbbjvj9+5Nnz59FBcX5358ySWXSMp537ndd999Ho8//vhjxcbG6vLLL/f4PNq0aaPo6GiPn+vcP7spKSk6dOiQLrnkEh0/flwbN26UJK1YsUIHDhzQvffe63GBxoABAxQLine truncated
"text/plain": [
"<Figure size 700x700 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Assuming the previous code has been executed and all_times is populated\n",
"\n",
"# Calculate the average time for each thread count\n",
"average_times = [sum(times) / len(times) for times in all_times]\n",
"\n",
"# max_threads = 64\n",
"# Thread counts\n",
"thread_counts = [1,2,4,8,16,32,64]\n",
"# Plotting the running time bar graph\n",
"plt.figure(figsize=(7, 7))\n",
"plt.plot(thread_counts, average_times, color='skyblue', )\n",
"\n",
"# Adding titles and labels\n",
"plt.title('Average runtime by Thread Count (OpenMP C)')\n",
"plt.xlabel('Number of Threads')\n",
"plt.ylabel('Running time (s)')\n",
"plt.xticks(thread_counts)\n",
"\n",
"# plt.xscale('log', base=2)\n",
"# Display the bar graph\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAA1cAAAJwCAYAAABlHJvKAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/SrBM8AAAACXBIWXMAAA9hAAAPYQGoP6dpAABYHUlEQVR4nO3deVgV5f//8deRXQRcABFFxBUTt9QMNypNNMOlsjTNXVswM8uSNs0ltMWlckm/ppaZZi6llWamlqmVu5aSIgqmuJSAoKHB/P7ox/l0ZJGTg3D0+biuua7mnntm3nPOkXhxz9zHYhiGIQAAAADANSlV3AUAAAAAwI2AcAUAAAAAJiBcAQAAAIAJCFcAAAAAYALCFQAAAACYgHAFAAAAACYgXAEAAACACQhXAAAAAGACwhUAAAAAmIBwBQDXgcVi0ZgxY677eTdu3CiLxaJPP/30up87L/Pnz5fFYtH27duLu5RCKa73rSTJzs5WWFiYJkyYUNyl3NAuX76soKAgzZgxo7hLAXANCFcAHMa+ffv0wAMPKDg4WO7u7qpcubLuvvtuvfPOO8Vd2k3r6NGjslgshVqOHj1a3OUWqbS0NL366qtq2LChypQpIw8PD4WFhen555/XiRMnirs8SdKXX35pd1j8+OOPlZSUpKFDh+ba9ssvv6h3796qXLmy3NzcFBgYqF69eumXX34xqWJz/PtzOn78+Dz79OrVSxaLRWXKlLFpv+OOO2w+x+XLl1ezZs30/vvvKzs7u1Dnj4+P16OPPqrq1avL3d1d3t7eatmypaZNm6aLFy9KklxcXDRixAhNmDBBf/3117VdMIBi41zcBQBAYWzZskV33nmnqlatqsGDBysgIEBJSUnatm2bpk2bpieffLK4S7wp+fn56cMPP7Rpe+utt3T8+HFNmTIlV98b1ZEjR9SuXTslJiaqe/fuGjJkiFxdXbV3717NnTtXK1as0G+//VbcZerLL7/U9OnT7QpYb7zxhnr06CEfHx+b9uXLl6tnz54qX768Bg4cqJCQEB09elRz587Vp59+qsWLF6tbt24mX8G1cXd318cff6yXXnrJpj0jI0OfffaZ3N3d89yvSpUqio2NlSSdOXNGH3zwgQYOHKjffvtNEydOLPCcX3zxhbp37y43Nzf16dNHYWFhunTpkjZv3qyRI0fql19+0ezZsyVJ/fv316hRo7Ro0SINGDDAhCsGcN0ZAOAA7rnnHsPPz884d+5crm2nTp26/gXZSZIxevTo637eDRs2GJKMpUuXXrdzdurUyQgODs5z27x58wxJxs8//2z3cbOzs40LFy5cY3X2Kcz7dvnyZaNhw4ZG6dKlje+//z7X9tTUVOOFF14oogrtEx0dbdjzv/6dO3cakoxvvvnGpv3w4cNG6dKljdDQUOP06dM2286cOWOEhoYanp6eRnx8vCl1X6uEhARDknHfffcZkozdu3fbbP/oo48MFxcXIyoqyvD09LTZFhERYdSrV8+mLSMjw6hSpYrh6elpXLp0Kd/zHjlyxChTpowRGhpqnDhxItf2Q4cOGVOnTrVpu/fee43WrVvbe4kASghuCwTgEOLj41WvXj2VLVs21zZ/f3+bdYvFoqFDh+qjjz5SnTp15O7uriZNmui7777Lte/vv/+uAQMGqGLFinJzc1O9evX0/vvv5+qXmZmp0aNHq2bNmnJzc1NQUJCee+45ZWZm5ur39NNPy8/PT15eXurcubOOHz+e63j9+vVTtWrVcrWPGTNGFovlP19PfrKysvTCCy8oICBAnp6e6ty5s5KSkqzbR48eLRcXF505cybXvkOGDFHZsmVNvVUpMzNTI0aMkJ+fnzw9PdWtW7dc565WrZruvfderV27Vk2bNpWHh4fee+89SVJKSoqGDx+uoKAgubm5qWbNmpo0aVKu27TefPNNtWjRQhUqVJCHh4eaNGmS5/NnhX3f8rJs2TLt2bNHL774olq1apVru7e3d67nlZYuXaomTZrIw8NDvr6+6t27t37//XebPnfccYfuuOOOXMe78rOTc8vbm2++qdmzZ6tGjRpyc3NTs2bN9PPPP9vsN336dEmyuc2tICtXrpSrq6vatGlj0/7GG2/owoULmj17dq4RSV9fX7333nvKyMjQ66+/bm3P+WwfPHhQDz74oLy9vVWhQgU99dRTeX62Fi5caH2Nypcvrx49eth8ZnNeo7CwMP3666+68847Vbp0aVWuXNnmvP8WHh6ukJAQLVq0yKb9o48+UocOHVS+fPkCX48cpUuX1u23366MjIw8/83keP3115Wenq65c+eqUqVKubbXrFlTTz31lE3b3Xffrc2bN+vPP/8sVC0AShbCFQCHEBwcrB07dmj//v2F6r9p0yYNHz5cvXv31tixY/XHH3+oQ4cONvufOnVKt99+u7755hsNHTpU06ZNU82aNTVw4EBNnTrV2i87O1udO3fWm2++qaioKL3zzjvq2rWrpkyZooceesjmvIMGDdLUqVPVvn17TZw4US4uLurUqdM1X39hrqcgEyZM0BdffKHnn39ew4YN07p169SuXTvr8x6PPPKI/v77by1ZssRmv0uXLunTTz/V/fffn+8tU//Fk08+qT179mj06NF6/PHHtWrVqjyf6YmLi1PPnj119913a9q0aWrUqJEuXLigiIgILVy4UH369NHbb7+tli1bKiYmRiNGjLDZf9q0aWrcuLHGjh2r1157Tc7Ozurevbu++OILm37X8r59/vnnkv55DQtj/vz5evDBB+Xk5KTY2FgNHjxYy5cvV6tWrZSSklKoY+Rl0aJFeuONN/Too49q/PjxOnr0qO677z5dvnxZkvToo4/q7rvvliR9+OGH1qUgW7ZsUVhYmFxcXGzaV61apWrVqql169Z57temTRtVq1Yt1+ssSQ8++KD++usvxcbG6p577tHbb7+tIUOG2PSZMGGC+vTpo1q1amny5MkaPny41q9frzZt2uR6jc6dO6cOHTqoYcOGeuuttxQaGqrnn39eX331VZ619ezZU4sXL5ZhGJKks2fP6uuvv9bDDz9c4GtxpSNHjsjJySnPP/jkWLVqlapXr64WLVoU+rhNmjSRYRjasmWLXfUAKCGKe+gMAArj66+/NpycnAwnJycjPDzceO6554y1a9fmeUuOJEOSsX37dmvbsWPHDHd3d6Nbt27WtoEDBxqVKlUyzp49a7N/jx49DB8fH+staB9++KFRqlSpXLd8zZo1y5Bk/PDDD4ZhGMbu3bsNScYTTz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lGnTp3yvIU4R851F/azkSPn9T579qxd+wEoGZgtEIDDaNasmZYvX65Lly5pz549WrFihaZMmaIHHnhAu3fv1i233GLtW6tWrVz7165dWxcuXNCZM2dUqlQppaSkaPbs2daZuq50+vRpSdKhQ4d04MCBfGe7y+l37NgxlSpVSjVq1LDZXqdOnf90vf92tesJCAiwa3+LxaKaNWvaTI/+0EMPafjw4froo4/0yiuvKDU1VatXr9bTTz991Wdz7FW1alWb9ZxfKM+dO2fTHhISkmvfQ4cOae/evVd9PyRp9erVGj9+vHbv3m3zfNy/r+da3zdvb+9CB5ic8JjXsUNDQ7V58+ZCHScvhX1N7WX8/9vncuSEhZyQlZ/8QtiVn8UaNWqoVKlS1s/ioUOHZBhGnp95SbluUaxSpUquz2e5cuW0d+/efGt7+OGH9dZbb+npp5/Wli1b9MILLxR4LdWqVdOcOXNksVjk7u6uWrVq5XrW80re3t6Srv46XSnn9Tb73xyA64NwBcDhuLq6qlmzZmrWrJlq166t/v37a+nSpRo9enShj5Ez8UHv3r3Vt2/fPPs0aNDA2rd+/fqaPHlLine truncated
"text/plain": [
"<Figure size 1000x700 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Calculate speedup compared to single-threaded execution\n",
"speedup = [average_times[0] / time for time in average_times]\n",
"\n",
"# Plotting the speedup bar graph\n",
"plt.figure(figsize=(10, 7))\n",
"plt.bar(thread_counts, speedup, color='skyblue')\n",
"\n",
"# Adding titles and labels\n",
"plt.title('Speedup by Thread Count (OpenMP C)')\n",
"plt.xlabel('Number of Threads')\n",
"plt.ylabel('Speedup Factor')\n",
"plt.xticks(thread_counts)\n",
"\n",
"\n",
"# Display the bar graph\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
@@ -0,0 +1,218 @@
import matplotlib.pyplot as plt
# Provided program output as a string
program_output = """
Counting 3s sequentially...
finished counting 3s
count: 99994272
Time taken: 1.528885 seconds
Counting 3s sequentially...
finished counting 3s
count: 100004192
Time taken: 1.521651 seconds
Counting 3s sequentially...
finished counting 3s
count: 100000476
Time taken: 1.523760 seconds
Counting 3s sequentially...
finished counting 3s
count: 100014445
Time taken: 1.524873 seconds
Counting 3s sequentially...
finished counting 3s
count: 100024069
Time taken: 1.527630 seconds
Counting 3s sequentially...
finished counting 3s
count: 100009123
Time taken: 0.762074 seconds
Counting 3s sequentially...
finished counting 3s
count: 100015500
Time taken: 0.763967 seconds
Counting 3s sequentially...
finished counting 3s
count: 100008976
Time taken: 0.763413 seconds
Counting 3s sequentially...
finished counting 3s
count: 100010319
Time taken: 0.764237 seconds
Counting 3s sequentially...
finished counting 3s
count: 99981263
Time taken: 0.762605 seconds
Counting 3s sequentially...
finished counting 3s
count: 100003901
Time taken: 0.442879 seconds
Counting 3s sequentially...
finished counting 3s
count: 100003640
Time taken: 0.382068 seconds
Counting 3s sequentially...
finished counting 3s
count: 100020536
Time taken: 0.381934 seconds
Counting 3s sequentially...
finished counting 3s
count: 100000475
Time taken: 0.385530 seconds
Counting 3s sequentially...
finished counting 3s
count: 100004132
Time taken: 0.381731 seconds
Counting 3s sequentially...
finished counting 3s
count: 99996709
Time taken: 0.254787 seconds
Counting 3s sequentially...
finished counting 3s
count: 100003625
Time taken: 0.191506 seconds
Counting 3s sequentially...
finished counting 3s
count: 100003638
Time taken: 0.254230 seconds
Counting 3s sequentially...
finished counting 3s
count: 100003219
Time taken: 0.191384 seconds
Counting 3s sequentially...
finished counting 3s
count: 100012445
Time taken: 0.191317 seconds
Counting 3s sequentially...
finished counting 3s
count: 99987909
Time taken: 0.133211 seconds
Counting 3s sequentially...
finished counting 3s
count: 100006337
Time taken: 0.096643 seconds
Counting 3s sequentially...
finished counting 3s
count: 99997158
Time taken: 0.096577 seconds
Counting 3s sequentially...
finished counting 3s
count: 100008637
Time taken: 0.125293 seconds
Counting 3s sequentially...
finished counting 3s
count: 99994796
Time taken: 0.131650 seconds
Counting 3s sequentially...
finished counting 3s
count: 99977435
Time taken: 0.075728 seconds
Counting 3s sequentially...
finished counting 3s
count: 100004478
Time taken: 0.074724 seconds
Counting 3s sequentially...
finished counting 3s
count: 100004689
Time taken: 0.076790 seconds
Counting 3s sequentially...
finished counting 3s
count: 100000961
Time taken: 0.070120 seconds
Counting 3s sequentially...
finished counting 3s
count: 99989321
Time taken: 0.096495 seconds
Counting 3s sequentially...
finished counting 3s
count: 99991306
Time taken: 0.072446 seconds
Counting 3s sequentially...
finished counting 3s
count: 100012069
Time taken: 0.081696 seconds
Counting 3s sequentially...
finished counting 3s
count: 99989876
Time taken: 0.079536 seconds
Counting 3s sequentially...
finished counting 3s
count: 99990048
Time taken: 0.091937 seconds
Counting 3s sequentially...
finished counting 3s
count: 99999415
Time taken: 0.065238 seconds
"""
# Split the output into lines
lines = program_output.strip().split("\n")
# Initialize lists to hold the times for each thread count
times_1_thread = []
times_2_threads = []
times_4_threads = []
times_8_threads = []
times_16_threads = []
times_32_threads = []
times_64_threads = []
# Initialize a list of lists to make it easier to append in a loop
all_times = [
times_1_thread,
times_2_threads,
times_4_threads,
times_8_threads,
times_16_threads,
times_32_threads,
times_64_threads,
]
# Current thread count index
thread_count_index = 0
# Parse the output and fill the lists
for line in lines:
if "Time taken:" in line:
# Extract the time taken from the line
time_taken = float(line.split()[-2])
# Append the time to the appropriate list
all_times[thread_count_index].append(time_taken)
# Check if the current thread count's list is filled with 5 runs
if len(all_times[thread_count_index]) == 5:
# Move to the next thread count
thread_count_index += 1
# Now all_times contains the lists of times for each thread count
print("Times for 1 thread:", times_1_thread)
print("Times for 2 threads:", times_2_threads)
print("Times for 4 threads:", times_4_threads)
print("Times for 8 threads:", times_8_threads)
print("Times for 16 threads:", times_16_threads)
print("Times for 32 threads:", times_32_threads)
print("Times for 64 threads:", times_64_threads)
# Assuming the previous code has been executed and all_times is populated
# Calculate the average time for each thread count
average_times = [sum(times) / len(times) for times in all_times]
# Calculate speedup compared to single-threaded execution
speedup = [average_times[0] / time for time in average_times]
# Thread counts
thread_counts = [1, 2, 4, 8, 16, 32]
# Plotting the speedup bar graph
plt.figure(figsize=(10, 6))
plt.bar(thread_counts, speedup, color='skyblue')
# Adding titles and labels
plt.title('Speedup by Thread Count')
plt.xlabel('Number of Threads')
plt.ylabel('Speedup Factor')
plt.xticks(thread_counts)
# Display the bar graph
plt.show()
+42
View File
@@ -0,0 +1,42 @@
1 threads
count: 994, Time taken: 0.000030
count: 994, Time taken: 0.000026
count: 994, Time taken: 0.000028
count: 994, Time taken: 0.000028
count: 994, Time taken: 0.000054
2 threads
count: 994, Time taken: 0.000057
count: 994, Time taken: 0.000055
count: 994, Time taken: 0.000061
count: 994, Time taken: 0.000063
count: 994, Time taken: 0.000061
4 threads
count: 994, Time taken: 0.000080
count: 994, Time taken: 0.000083
count: 994, Time taken: 0.000082
count: 994, Time taken: 0.000076
count: 994, Time taken: 0.000081
8 threads
count: 994, Time taken: 0.000111
count: 994, Time taken: 0.000120
count: 994, Time taken: 0.000112
count: 994, Time taken: 0.000132
count: 994, Time taken: 0.000140
16 threads
count: 994, Time taken: 0.000183
count: 994, Time taken: 0.000182
count: 994, Time taken: 0.000199
count: 994, Time taken: 0.000183
count: 994, Time taken: 0.000189
32 threads
count: 994, Time taken: 0.000495
count: 994, Time taken: 0.000435
count: 994, Time taken: 0.000462
count: 994, Time taken: 0.000368
count: 994, Time taken: 0.000407
64 threads
count: 994, Time taken: 0.000711
count: 994, Time taken: 0.000740
count: 994, Time taken: 0.000732
count: 994, Time taken: 0.000727
count: 994, Time taken: 0.000860
+8
View File
@@ -0,0 +1,8 @@
# compile and run cuda_test.cpp
all:
nvcc -o cuda_test cuda_test.cu
./cuda_test
clean:
rm -f cuda_test
View File
Whitespace-only changes.
+119
View File
@@ -0,0 +1,119 @@
// example cuda program
//
// Created by Ziad Arafat
#include <iostream>
#include <cuda.h>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
#include <stdlib.h>
using namespace std;
// kernel function to add up the elements of a vector using reduce algorithm
__global__ void reduce(int *g_idata, int *g_odata)
{
extern __shared__ int sdata[];
// each thread loads one element from global to shared mem
unsigned int tid = threadIdx.x;
unsigned int i = blockIdx.x * blockDim.x + threadIdx.x;
sdata[tid] = g_idata[i];
__syncthreads();
// do reduction in shared mem
for (unsigned int s = 1; s < blockDim.x; s *= 2)
{
if (tid % (2 * s) == 0)
{
sdata[tid] += sdata[tid + s];
}
__syncthreads();
}
// write result for this block to global mem
if (tid == 0)
g_odata[blockIdx.x] = sdata[0];
}
__global__ void vector_add(int *a, int *b, int *c, int N)
{
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < N)
{
c[i] = a[i] + b[i];
}
}
int main(int argc, char const *argv[])
{
// size of the vector
int N = pow(2, 11);
// size of the vector in bytes
size_t bytes = N * sizeof(int);
// host vectors
int *h_a, *h_b;
// allocate memory for host vectors
h_a = (int *)malloc(bytes);
h_b = (int *)malloc(bytes);
// initialize host vectors
for (int i = 0; i < N; i++)
{
// generate a random number
srand(1); // set the seed to current time
h_a[i] = rand() % 1000;
// cout << h_a[i] << " ";
}
// device vectors
int *d_a, *d_b;
// allocate memory for device vectors
cudaMalloc(&d_a, bytes);
cudaMalloc(&d_b, bytes);
// copy data from host to device
cudaMemcpy(d_a, h_a, bytes, cudaMemcpyHostToDevice);
// number of threads per block
int NUM_THREADS = 1024;
// number of blocks
int NUM_BLOCKS = (N + NUM_THREADS - 1) / NUM_THREADS;
// number of bytes for shared memory
int SHMEM_BYTES = NUM_THREADS * sizeof(int);
// execute kernel
reduce<<<NUM_BLOCKS, NUM_THREADS, SHMEM_BYTES>>>(d_a, d_b);
// copy data from device to host
cudaMemcpy(h_b, d_b, bytes, cudaMemcpyDeviceToHost);
// print the result
cout << "The sum is " << h_b[0] << endl;
// test if result is correct
int sum = 0;
for (int i = 0; i < N; i++)
{
sum += h_a[i];
}
cout << "The sum is " << sum << endl;
// free device memory
cudaFree(d_a);
cudaFree(d_b);
// free host memory
free(h_a);
free(h_b);
return 0;
}
+94
View File
@@ -0,0 +1,94 @@
import java.util.*;
public class CountThrees implements Runnable {
private static int ARRAY_LENGTH;
private static int MAX_THREADS;
private static final int MAX_RANGE = 100;
private static final Random random = new Random();
private static int count = 0;
private static final Object lock = new Object();
private static int[] array;
private static Thread[] threads;
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Usage: java CountThrees <array_length> <max_threads>");
System.exit(1);
}
try {
ARRAY_LENGTH = Integer.parseInt(args[0]);
MAX_THREADS = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
System.err.println("Invalid argument: " + args[0] + " or " + args[1] + " is not a valid integer");
System.exit(1);
}
array = new int[ARRAY_LENGTH];
// Initialize the elements in the array
for (int i = 0; i < array.length; i++) {
array[i] = random.nextInt(MAX_RANGE);
}
long startTime = System.nanoTime();
// Create the threads
CountThrees[] counters = new CountThrees[MAX_THREADS];
int lengthPerThread = ARRAY_LENGTH / MAX_THREADS;
for (int i = 0; i < counters.length; i++) {
counters[i] = new CountThrees(
i * lengthPerThread,
lengthPerThread
);
}
// Run the threads
threads = new Thread[MAX_THREADS];
for (int i = 0; i < counters.length; i++) {
threads[i] = new Thread(counters[i]);
threads[i].start();
}
for (int i = 0; i < counters.length; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
// Do nothing
}
}
long endTime = System.nanoTime();
// Print the number of threes
System.out.println("Number of threes: " + count);
// compute the elapsed time in nanoseconds
long duration = (endTime - startTime);
// convert to seconds
double seconds = (double)duration / 1_000_000_000.0;
System.out.println("Time taken: " + seconds + " seconds");
}
private int startIndex;
private int elements;
private int myCount = 0;
public CountThrees(int start, int elem) {
startIndex = start;
elements = elem;
}
// Overload of run method in the Thread class
public void run() {
// Count the number of threes
for (int i = 0; i < elements; i++) {
if (array[startIndex + i] == 3) {
myCount++;
}
}
// synchronized (lock) {
// count += myCount;
// }
count += myCount;
}
}
+16
View File
@@ -0,0 +1,16 @@
all: CountThrees.class
CountThrees.class:
javac CountThrees.java
run:
for threads in 1 2 4 8 16 32 64; do \
echo "$$threads threads" >> results.txt; \
for i in {1..5}; do \
java CountThrees 1000000000 $$threads >> results.txt; \
done \
done
clean:
rm -f CountThrees.class results.txt
@@ -0,0 +1,261 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Times for 1 thread: [0.359876473, 0.361032238, 0.360004483, 0.359855544, 0.359787787]\n",
"Times for 2 threads: [0.373749715, 0.447702756, 0.464235889, 0.372059609, 0.371326817]\n",
"Times for 4 threads: [0.222983097, 0.216992067, 0.21719135, 0.21907073, 0.22178881]\n",
"Times for 8 threads: [0.167658194, 0.165304926, 0.163078056, 0.162809502, 0.165746493]\n",
"Times for 16 threads: [0.178607489, 0.172914077, 0.174337312, 0.176571896, 0.175561715]\n",
"Times for 32 threads: [0.190420432, 0.190276435, 0.178388981, 0.180038991, 0.149067537]\n",
"Times for 64 threads: [0.160374063, 0.229213367, 0.282740373, 0.19328029, 0.199149752]\n"
]
}
],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
" # Provided program output as a string\n",
"program_output = \"\"\"\n",
"1 threads\n",
"Number of threes: 9997807\n",
"Time taken: 0.359876473 seconds\n",
"Number of threes: 9998567\n",
"Time taken: 0.361032238 seconds\n",
"Number of threes: 9996883\n",
"Time taken: 0.360004483 seconds\n",
"Number of threes: 9996455\n",
"Time taken: 0.359855544 seconds\n",
"Number of threes: 9998718\n",
"Time taken: 0.359787787 seconds\n",
"2 threads\n",
"Number of threes: 9998562\n",
"Time taken: 0.373749715 seconds\n",
"Number of threes: 10004232\n",
"Time taken: 0.447702756 seconds\n",
"Number of threes: 10000537\n",
"Time taken: 0.464235889 seconds\n",
"Number of threes: 9997416\n",
"Time taken: 0.372059609 seconds\n",
"Number of threes: 9996787\n",
"Time taken: 0.371326817 seconds\n",
"4 threads\n",
"Number of threes: 10004804\n",
"Time taken: 0.222983097 seconds\n",
"Number of threes: 9997107\n",
"Time taken: 0.216992067 seconds\n",
"Number of threes: 10000709\n",
"Time taken: 0.21719135 seconds\n",
"Number of threes: 9996199\n",
"Time taken: 0.21907073 seconds\n",
"Number of threes: 10008067\n",
"Time taken: 0.22178881 seconds\n",
"8 threads\n",
"Number of threes: 10006502\n",
"Time taken: 0.167658194 seconds\n",
"Number of threes: 10004407\n",
"Time taken: 0.165304926 seconds\n",
"Number of threes: 9997402\n",
"Time taken: 0.163078056 seconds\n",
"Number of threes: 9999915\n",
"Time taken: 0.162809502 seconds\n",
"Number of threes: 9999852\n",
"Time taken: 0.165746493 seconds\n",
"16 threads\n",
"Number of threes: 9997128\n",
"Time taken: 0.178607489 seconds\n",
"Number of threes: 9995240\n",
"Time taken: 0.172914077 seconds\n",
"Number of threes: 10001920\n",
"Time taken: 0.174337312 seconds\n",
"Number of threes: 10000932\n",
"Time taken: 0.176571896 seconds\n",
"Number of threes: 10005193\n",
"Time taken: 0.175561715 seconds\n",
"32 threads\n",
"Number of threes: 9998869\n",
"Time taken: 0.190420432 seconds\n",
"Number of threes: 10000228\n",
"Time taken: 0.190276435 seconds\n",
"Number of threes: 9372724\n",
"Time taken: 0.178388981 seconds\n",
"Number of threes: 10000496\n",
"Time taken: 0.180038991 seconds\n",
"Number of threes: 9997442\n",
"Time taken: 0.149067537 seconds\n",
"64 threads\n",
"Number of threes: 9687065\n",
"Time taken: 0.160374063 seconds\n",
"Number of threes: 9996783\n",
"Time taken: 0.229213367 seconds\n",
"Number of threes: 9997292\n",
"Time taken: 0.282740373 seconds\n",
"Number of threes: 9530897\n",
"Time taken: 0.19328029 seconds\n",
"Number of threes: 9689583\n",
"Time taken: 0.199149752 seconds \n",
"\"\"\"\n",
"\n",
"# Split the output into lines\n",
"lines = program_output.strip().split(\"\\n\")\n",
"\n",
"# Initialize lists to hold the times for each thread count\n",
"times_1_thread = []\n",
"times_2_threads = []\n",
"times_4_threads = []\n",
"times_8_threads = []\n",
"times_16_threads = []\n",
"times_32_threads = []\n",
"times_64_threads = []\n",
"\n",
"# Initialize a list of lists to make it easier to append in a loop\n",
"all_times = [\n",
" times_1_thread,\n",
" times_2_threads,\n",
" times_4_threads,\n",
" times_8_threads,\n",
" times_16_threads,\n",
" times_32_threads,\n",
" times_64_threads,\n",
"]\n",
"\n",
"# Current thread count index\n",
"thread_count_index = 0\n",
"\n",
"# Parse the output and fill the lists\n",
"for line in lines:\n",
" if \"Time taken:\" in line:\n",
" # Extract the time taken from the line\n",
" time_taken = float(line.split()[-2])\n",
" # Append the time to the appropriate list\n",
" all_times[thread_count_index].append(time_taken)\n",
" # Check if the current thread count's list is filled with 5 runs\n",
" if len(all_times[thread_count_index]) == 5:\n",
" # Move to the next thread count\n",
" thread_count_index += 1\n",
"\n",
"# Now all_times contains the lists of times for each thread count\n",
"print(\"Times for 1 thread:\", times_1_thread)\n",
"print(\"Times for 2 threads:\", times_2_threads)\n",
"print(\"Times for 4 threads:\", times_4_threads)\n",
"print(\"Times for 8 threads:\", times_8_threads)\n",
"print(\"Times for 16 threads:\", times_16_threads)\n",
"print(\"Times for 32 threads:\", times_32_threads)\n",
"print(\"Times for 64 threads:\", times_64_threads)\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAm4AAAJwCAYAAAAwdO34AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/SrBM8AAAACXBIWXMAAA9hAAAPYQGoP6dpAABvHklEQVR4nO3deXhTZf7+8Tt791IoFAoFWlA2WRQUQWURpCCiuA3M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lJRowoQJatu2rRwOhzIyMnT33XerpKQk4L6+86Bmz56tTp06yeFwaN68eZKkxx9/XL1791ajRo0UGxur7t2765133qny+MXFxbr11luVmpqqxMREnX/++dq2bZtMJpMefPDBgH23bdumq666SmlpaXI4HOrUqZNeffXVo37NfOepLF++XH369FFcXJx/aKe6x5fKhvgqd8x854988803GjdunBo3bqz4+HhdeOGF2r17d8D9fv31Vy1atKjKsEt157j5alu1apX69u2ruLg4tW3b1v8aLlq0SD179lRsbKzatWunL774okqttfF6zZ49W+3atVNMTIy6d++ur776yn/bggULZDKZ9P7771e535tvvimTyaQlS5YE9XhH8uKLL6pNmzZyOBw69dRT9f333wfcPnr0aCUkJGj9+vU699xzlZiYqMsuu0xS2R8W06ZNU6dOnRQTE6O0tDRdd9112r9/f8Ax/vvf/2ro0KFKT0+Xw+FQmzZtNHHiRHk8nkPWExsbq9NOO01ff/11jZ7H1q1b9cILL+icc86pEtokyWKx6M477wzotv34448aMmSIkpKSlJCQoAEDBmjp0qUB9/MN+R2suvOcWrdurfPOO0+LFy/WaaedppiYGGVlZenf//53wP0uvfRSSVL//v39793DnY+5ePFi7dmzRwMHDjzi67Bv3z7deeed6ty5sxISEpSUlKQhQ4bop59+8u+zc+dOWa1WPfTQQ1Xuv3btWplMJj377LM1Pl5t+u2339S/f3/FxcWpefPmeuyxxwJu9/3fnjNnjv7v//5PzZs3V1xcnJxOpyTpu+++0+DBg5WcnKy4uDj17dtX33zzTcAxNm3apBtvvFHt2rVTbGysGjVqpEsvvbTaP2h+/fVXnX322YqNjVWLFi30yCOPyOv1Vtnvhx9+UHZ2tlJTUxUbG6vMzExdddVVVfY755xz9OGHH8owjGN4laIPHTfUyOzZs3XRRRfJbrfrr3/9q6ZPn67vv/9ep556qmw2my688EK99957euGFFwKG5D744AOVlJRo5MiRksp+uZ1//vlavHixrr32WnXo0EE///yzpk6dqt9//10ffPBBwON++eWXeuutt3TzzTcrNTXV3y156qmndP755+uyyy6Ty+XSnDlzdOmll+qjjz7S0KFD/fcfPXq03nrrLV1xxRU6/fTTtWjRooDbfXbu3KnTTz/dHxYbN26sTz75RFdffbWcTme1v/xqYu/evRoyZIhGjhypyy+//KiHQm655RalpKRowoQJ2rhxo6ZNm6abb75Zc+fOlVQ2NHjLLbcoISFB9913n6QjD7vs379f5513nkaOHKlLL71U06dP18iRIzV79myNHTtW119/vf72t7/pX//6ly655BJt2bJFiYmJkmrn9Vq0aJHmzp2rW2+9VQ6HQ88//7wGDx6sZcuW6aSTTlK/fv2UkZGh2bNn68ILLwy47+zZs9WmTRv16tXrKF7N6r355pvKz8/XddddJ5PJpMcee0wXXXSRNmzYIJvN5t+vtLRU2dnZOvPMM/X444/7O6jXXXedZs2apTFjxujWW29VTk6Onn32Wf3444/65ptv/MeYNWuWEhISNG7cOCUkJOjLL7/UAw88IKfTqX/961/+x3nllVd03XXXqXfv3ho7dqw2bNig888/Xw0bNlRGRsZhn8snn3yi0tJSXXHFFTV67r/++qvOOussJSUl6e6775bNZtMLL7ygfv36+UP80Vi3bp0uueQSXX311Ro1apReffVVjR49Wt27d1enTp3Up08f3XrrrXr66af1j3/8Qx06dJAk/7/V+fbbb2UymXTyyScf8fE3bNigDz74QJdeeqkyMzO1c+dOvfDCC+rbt69+++03paenKy0tTX379tVbb71VZRRh7ty5slgs/nBZk+PVlv3792vw4MG66KKL9Je//EXvvPOO7rnnHnXu3FlDhgwJ2HfixImy2+268847VVJSIrvdri+//FJDhgxR9+7dNWHCBJnNZs2cOVNnn322vv76a5122mmSpO+//17ffvutRo4cqRYtWmjjxo2aPn26+vXrp99++83//t6xY4f69++v0tJS3XvvvYqPj9eLL76o2NjYgFp27dqlQYMGqXHjxrr33nvVoEEDbdy4Ue+9916V59i9e3dNnTpVv/76a9hMxqgXDOAIfvjhB0OS8fnnnxuGYRher9do0aKFcdttt/n3+fTTTw1Jxocffhhw33PPPdfIysryf/36668bZrPZ+PrrrwP2mzFjhiHJ+Oabb/zbJBlms9n49ddfq9RUVFQU8LXL5TJOOukk4+yzz/ZvW758uSHJGDt2bMC+o0ePNiQZEyZM8G+7+uqrjWbNmhl79uwJ2HfkyJFGcnJylcerib59+xqSjBkzZlS57eDH92nVqpUxatQo/9czZ840JBkDBw40vF6vf/vtt99uWCwWIzc317+tU6dORt++fascc8GCBYYkY8GCBVVqe/PNN/3b1qxZ43/Nly5d6t/u+97OnDnTv+1YXy9JhiTjhx9+8G/btGmTERMTY1x44YX+bePHjzccDkfA89y1a5dhtVqrff0O5V//+pchycjJyalyW05OjiHJaNSokbFv3z7/9v/+979V3tOjRo0yJBn33ntvwDG+/vprQ5Ixe/bsgO3z5s2rsr261+a6664z4uLijAMHDhiGUfZ+btKkidGtWzejpKTEv9+LL75oSKr2+1zZ7bffbkgyfvzxx8Pu5zN8+HDDbrcb69ev92/bvn27kZiYaPTp08e/bcKECUZ1vzZ879PKr2+rVq0MScZXX33l37Zr1y7D4XAYd9xxh3/b22+/XeX9eTiXX3650ahRoyrbfd/Hf/3rX/5tBw4cMDweT5X9HA6H8fDDD/u3vfDCC4Yk4+effw7Yt2PHjgE/U2p6vCPZvXv3IX8GGEbF/89///vf/m0lJSVG06ZNjYsvvti/zfd/OysrK+B95fV6jRNOOMHIzs4O+LlRVFRkZGZmGuecc07AtoMtWbKkyuOPHTvWkGR89913/m27du0ykpOTA77377//viHJ+P7774/4Onz77beGJGPu3LlH3BcVGCrFEc2ePVtpaWn+E4FNJpNGjBihOXPm+Id3zj77bKWmpvo7QFLZX4yff/65RowY4d/29ttvq0OHDmrfvr327Nnj//Cd47BgwYKAx+7bt686duxYpabKf+Xt379feXl5Ouuss7RixQr/dt+w6o033hhw31tuuSXga8Mw9O6772rYsGEyDCOgruzsbOXl5QUcNxgOh6PaIeRgXXvttQFDVGeddZY8Ho82bdp01MdMSEjwd0IlqV27dmrQoIE6dOgQ0GHxfb5hwwZJtfd69erVS927d/d/3bJlS11wwQX69NNP/e+rK6+8UiUlJQHD4HPnzlVpaWmtnxs0YsQIpaSk+L8+66yzJFU878puuOGGgK/ffvttJScn65xzzgl4Pbp3766EhISA93Xl925+fr727Nmjs846S0VFRVqzZo2ksqGmXbt26frrrw/oYI8ePVrJyclHfC6+oTJfh/RwPB6PPvvsMw0fPlxZWVn+7c2aNdPf/vY3LV682H+8YHXs2NH/OkpS48aN1a5du2pf05rau3dvwPfpcBwOh/9cL4/Line truncated
"text/plain": [
"<Figure size 700x700 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Assuming the previous code has been executed and all_times is populated\n",
"\n",
"# Calculate the average time for each thread count\n",
"average_times = [sum(times) / len(times) for times in all_times]\n",
"\n",
"# max_threads = 64\n",
"# Thread counts\n",
"thread_counts = [1,2,4,8,16,32,64]\n",
"# Plotting the running time bar graph\n",
"plt.figure(figsize=(7, 7))\n",
"plt.plot(thread_counts, average_times, color='skyblue', )\n",
"\n",
"# Adding titles and labels\n",
"plt.title('Average runtime by Thread Count (Java Threads)')\n",
"plt.xlabel('Number of Threads')\n",
"plt.ylabel('Running time (s)')\n",
"plt.xticks(thread_counts)\n",
"\n",
"# plt.xscale('log', base=2)\n",
"# Display the bar graph\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAA04AAAJwCAYAAAC+pzHoAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/SrBM8AAAACXBIWXMAAA9hAAAPYQGoP6dpAABM+0lEQVR4nO3deXyM5/7/8ffILpFYE2tCbUEQWyu0opUKVUsXRbX2paexVdHm9LSKo6GtvZbqadGi1NpWa6va6VE7LVpqiZ2DRFAquX9/+JmvacKVYWKC1/PxmMejc93Xfc3nnrmTeue672tslmVZAgAAAADcVA53FwAAAAAA2R3BCQAAAAAMCE4AAAAAYEBwAgAAAAADghMAAAAAGBCcAAAAAMCA4AQAAAAABgQnAAAAADAgOAEAAACAAcEJADJgs9n07rvv3vXXXbFihWw2m2bPnn3XXzsjkydPls1m08aNG91dSqa463PLTtLS0hQREaHBgwe7u5QsYbPZ1K1bN3eXkSnt2rVT8eLFndpn0aJFCggI0KlTp7KmKAC3jeAEIMvs2LFDzz//vMLCwuTr66siRYroySef1JgxY9xd2gPrwIEDstlsmXocOHDA3eVmqeTkZA0YMECVK1dWQECA/Pz8FBERoTfeeENHjx51d3mSpO+//97pIPjll18qMTHRIVxk5wBct27dTJ2PD0ogbtCggUqVKqWEhAR3lwLgbzzdXQCA+9O6dev0+OOPKzQ0VJ07d1bBggWVmJion376SaNGjVL37t3dXeIDqUCBAvriiy8c2oYNG6bDhw9rxIgR6frer/744w/FxMTo0KFDat68ubp06SJvb29t375dn376qebNm6fffvvN3WXq+++/19ixY50KDR988IFatmypoKCgrCvMhd566y116tTJ/vznn3/W6NGj9c9//lPlypWzt1eqVMkd5blF165d1adPHw0YMEC5cuVydzkA/j+CE4AsMXjwYAUFBennn39W7ty5HbadPHnSPUVB/v7+eumllxzaZsyYobNnz6Zrv1OWZenPP/+Un5+fS8e9U1evXtWzzz6rEydOaMWKFXr00Ucdtg8ePFhDhw51U3V3ZsuWLdq2bZuGDRvm7lIy7cknn3R47uvrq9GjR+vJJ59U3bp1XfpaFy5ckL+/v0vHzArPPfecunfvrlmzZqlDhw7uLgfA/8elegCyxL59+1ShQoV0oUmSgoODHZ5fv2dh2rRpKlu2rHx9fVWtWjWtWrUq3b5HjhxRhw4dFBISIh8fH1WoUEGfffZZun6XL19W//79VapUKfn4+KhYsWLq16+fLl++nK7fa6+9pgIFCihXrlxq0qSJDh8+nG68m92r8O6778pms9328dxMamqq/vnPf6pgwYLy9/dXkyZNlJiYaN/ev39/eXl5ZXgfRJcuXZQ7d279+eefmX49k8uXL6t3794qUKCA/P399cwzz6R77eLFi+vpp5/W4sWLVb16dfn5+enjjz+WJJ07d069evVSsWLF5OPjo1KlSmno0KFKS0tzGOPDDz9UrVq1lC9f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KFC9pqv9/nvf/+rffv22dumTZumYsWKpZsduFNdunRxmDF47LHHlJqaqoMHDzr0K1GihGJjYx3aZs2apccee0x58uRx+DxiYmKUmprqcAnjjfdDnT17VklJSXrsscfsn610559bcnJypm+437hxo06ePKlXX33VYQavUaNGCg8P13fffZepcTLSokUL5cmTx/78sccek3Rt4Yrb9b///c9hzFu58b3+888/dfr0adWsWVOSHN7vFi1a6OTJk1qxYoW9bfbs2UpLS1OLFi2cHs8VYmJiVLJkSfvzSpUqKTAwMMP37pVXXnF4PnfuXKWlpemFF15wOB8LFiyo0qVL238//P2YLly4oNOnT6tWrVqyLEtbtmyRJB07dkxbt25V27ZtHRbkePLJJ1W+fHmH186dO7cuXLigpUuXGo/x+ud4+vRpY18AdwfBCUCWqVGjhubOnauzZ89qw4YNio+P1/nz5/X888/r119/dehbunTpdPuXKVNGFy9e1KlTp3Tq1CmdO3dOEydOVIECBRwe7du3l/R/i078/vvv+uWXX9L1K1OmjEO/gwcPKkeOHA7/AJOksmXL3vGxm47H2f1tNptKlSrlsER4ixYt5OPjo2nTpkmSkpKStGDBArVu3dqll0VJ14Lfja7/o+7s2bMO7SVKlEi37++//65Fixal+zxiYmIkOS4WsmDBAtWsWVO+vr7KmzevChQooPHjxyspKcne504/t8DAQJ0/fz5Tfa8Hw4zGDg8PTxccnZHZ99RZ1v+/HM3kzJkz6tmzp0JCQuTn56cCBQrYP78b3+8GDRooKCjI4bLMmTNnKjIy0v4z5cx4rvD390669v5l9N79/Zz8/fffZVmWSpcune6c3LVrl8P5eOjQIbVr10558+ZVQECAChQoYP+jxPVjun4OZPQz//fz5tVXX1WZMmXUsGFDFS1aVB06dEh3b9Z11z9HV/8sA7h93OMEIMt5e3urRo0aqlGjhsqUKaP27dtr1qxZ6t+/f6bHuL6IwEsvvaS2bdtm2Of6csVpaWmqWLGihg8fnmG/YsWKOXkEN//HS2Zmj7JKnjx59PTTT2vatGl65513NHv2bF2+fNnlq+NJkoeHR4btf/9HekYr6KWlpenJJ59Uv379Mhzj+j++V69erSZNmqhOnToaN26cChUqJC8vL02aNEnTp0+/wyP4P+HLine truncated
"text/plain": [
"<Figure size 1000x700 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Calculate speedup compared to single-threaded execution\n",
"speedup = [average_times[0] / time for time in average_times]\n",
"\n",
"# Plotting the speedup bar graph\n",
"plt.figure(figsize=(10, 7))\n",
"plt.bar(thread_counts, speedup, color='skyblue')\n",
"\n",
"# Adding titles and labels\n",
"plt.title('Speedup by Thread Count (Java Threads)')\n",
"plt.xlabel('Number of Threads')\n",
"plt.ylabel('Speedup Factor')\n",
"plt.xticks(thread_counts)\n",
"\n",
"\n",
"# Display the bar graph\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
+77
View File
@@ -0,0 +1,77 @@
1 threads
Number of threes: 9997807
Time taken: 0.359876473 seconds
Number of threes: 9998567
Time taken: 0.361032238 seconds
Number of threes: 9996883
Time taken: 0.360004483 seconds
Number of threes: 9996455
Time taken: 0.359855544 seconds
Number of threes: 9998718
Time taken: 0.359787787 seconds
2 threads
Number of threes: 9998562
Time taken: 0.373749715 seconds
Number of threes: 10004232
Time taken: 0.447702756 seconds
Number of threes: 10000537
Time taken: 0.464235889 seconds
Number of threes: 9997416
Time taken: 0.372059609 seconds
Number of threes: 9996787
Time taken: 0.371326817 seconds
4 threads
Number of threes: 10004804
Time taken: 0.222983097 seconds
Number of threes: 9997107
Time taken: 0.216992067 seconds
Number of threes: 10000709
Time taken: 0.21719135 seconds
Number of threes: 9996199
Time taken: 0.21907073 seconds
Number of threes: 10008067
Time taken: 0.22178881 seconds
8 threads
Number of threes: 10006502
Time taken: 0.167658194 seconds
Number of threes: 10004407
Time taken: 0.165304926 seconds
Number of threes: 9997402
Time taken: 0.163078056 seconds
Number of threes: 9999915
Time taken: 0.162809502 seconds
Number of threes: 9999852
Time taken: 0.165746493 seconds
16 threads
Number of threes: 9997128
Time taken: 0.178607489 seconds
Number of threes: 9995240
Time taken: 0.172914077 seconds
Number of threes: 10001920
Time taken: 0.174337312 seconds
Number of threes: 10000932
Time taken: 0.176571896 seconds
Number of threes: 10005193
Time taken: 0.175561715 seconds
32 threads
Number of threes: 9998869
Time taken: 0.190420432 seconds
Number of threes: 10000228
Time taken: 0.190276435 seconds
Number of threes: 9372724
Time taken: 0.178388981 seconds
Number of threes: 10000496
Time taken: 0.180038991 seconds
Number of threes: 9997442
Time taken: 0.149067537 seconds
64 threads
Number of threes: 9687065
Time taken: 0.160374063 seconds
Number of threes: 9996783
Time taken: 0.229213367 seconds
Number of threes: 9997292
Time taken: 0.282740373 seconds
Number of threes: 9530897
Time taken: 0.19328029 seconds
Number of threes: 9689583
Time taken: 0.199149752 seconds
+10
View File
@@ -0,0 +1,10 @@
all: count_threes
count_threes: count_threes.c
/usr/lib64/mpi/gcc/openmpi4/bin/mpicc -o count_threes count_threes.c
run:
/usr/lib64/mpi/gcc/openmpi4/bin/mpirun --hostfile remotes.txt -np 92 ./count_threes 10000000
clean:
rm -f count_threes
+117
View File
@@ -0,0 +1,117 @@
# README
# Tutorial
## Connecting to the machines
### Connect to your head node
1. SSH into a machine that has MPI Working.
1. One such example is `gojiro.cs.nmsu.edu`
2. Now let's refer to this machine as your head node.
3. How to tell if the machine has mpi?
1. Connect to the machine
2. try to run the command `mpirun --version` or `mpicc --version`
3. It should print out the version number. If not it probably doesn't
4. However sometimes your `PATH` is broken.
1. To check this run this command
1. `/usr/lib64/mpi/gcc/openmpi4/bin/mpicc --version`
2. If this command returns the version number of mpicc then your `PATH` is broken.
1. You don't have to fix it.
1. From now on you can just use `/usr/lib64/mpi/gcc/openmpi4/bin/mpicc` instead of `mpicc`
2. If you want to try fixing it you just need to add `/usr/lib64/mpi/gcc/openmpi4/bin/` to your `PATH`
1. [How to do this ](https://www.howtogeek.com/658904/how-to-add-a-directory-to-your-path-in-linux/)
### Connect to and setup your worker nodes
#### Find worker nodes that have mpi working.
1. Find at least 1 other worker that has mpi working.
2. Here is a list of known nodes (append `.cs.nmsu.edu` if you need to)
1. `kraken`
2. `gojiro`
3. `tsunami`
4. `kaiju`
5. `gray`
1. (`gray` had issues when I used it but if you use it as your head node it should work.)
#### Setup your worker nodes for no-password ssh login
1. This is necessary for mpi to be able to login to each node and execute commands without passwords
2. Don't worry this only allows your head node to do this. It is completely safe.
3. Steps
1. Generate a local ssh key
1. `ssh-keygen`
1. Press enter for default options
2. Copy the ssh key to one of the nodes you want to use
1. `ssh-copy-id yourusername@yournode.cs.nmsu.edu`
2. You only need to copy it to one node because the CS machines share the same files so copying it to one node will allow passwordless login on all of them.
5. Test the ssh connection to each node
1. for each node in your hostfile run this command
1. `ssh yourusername@nodename.cs.nmsu.edu`
2. each one should work without a password.
3. This step is crucial because ssh wants you to confirm you want each hostname in your list of known hosts.
#### Create your "hosts" file
1. Create a plain text file in your code directory
1. `touch mynodes.txt`
1. You can name it anything you like
2. Put the hostnames of each of your nodes including your head node line-by-line (example below)
##### Example hosts file
```
kraken
gojiro
tsunami
kaiju
```
## Compile and run your code
### Compile
1. compile your c program that uses mpi using `mpicc`
2. `mpicc -o hello hello.c`
### Run
1. Run your code using `mpirun` and determine the number of processor slots
2. `mpirun --hostfile remotes.txt -np 2 ./hello`
3. If you setup enough hosts at least 2 processors should work.
4. Slowly increase the number after `-np` until it stops working.
1. This will tell you the max number of processor slots your node cluster can provide.
2. In my case I was able to reach 100 slots with 5 machines
## Troubleshooting
### Duplicate hosts in hostfile
1. If you have duplicates in your hostfile or you included `localhost` as well as the public name of your head host your code will break
### The infamous newline issue
1. Sometimes having a newline at the bottom of your hosts file can break or fix things
2. Try with and without a blank line at the bottom of your hosts file
### My code is just stuck
1. Some nodes are broken like this.
1. Try removing hosts from your hostsfile one by one until you find the bad egg
---
# How to use my code...
## usage
1. Open your terminal and navigate to the directory containing the Makefile.
2. To compile the program, use the command: `make`
3. To run the program across multiple nodes, use the command: `make run`
4. To clean up the compiled files after you're done, use the command: `make clean`
## using the python script to setup hosts
1. Open your terminal and navigate to the directory containing the `setup_remotes.py` script.
2. Ensure you have the `paramiko` library installed. If not, install it using pip: `pip install paramiko`
3. Run the script with the following command: `python setup_remotes.py <hostsfile> <your-username> <your-password>`
## using the other python script to check if the hosts have mpi
1. it will output the hosts that have it to a new file
2. `python check_mpicc host_file username password output_file`
3. this also depends on `paramiko`
+33
View File
@@ -0,0 +1,33 @@
import argparse
import paramiko
parser = argparse.ArgumentParser(description='Connect to a list of hosts using SSH')
parser.add_argument('host_file', type=str, help='Path to file containing list of hosts')
parser.add_argument('username', type=str, help='Username for SSH connection')
parser.add_argument('password', type=str, help='Password for SSH connection')
parser.add_argument('output_file', type=str, help='Path to output file')
args = parser.parse_args()
with open(args.host_file, 'r') as f:
hosts = f.readlines()
for host in hosts:
print("Checking host: " + host.strip())
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host.strip(), username=args.username, password=args.password)
except:
continue
stdin, stdout, stderr = ssh.exec_command('/usr/lib64/mpi/gcc/openmpi4/bin/mpicc --version')
output = stdout.read().decode('utf-8')
error_output = stderr.read().decode('utf-8') # Read from stderr
if 'gcc (SUSE Linux) 7.5.0' not in output:
print('does not have mpicc installed\n')
else:
with open(args.output_file, 'a') as out_file:
out_file.write(f'{host.strip()}\n')
ssh.close()
ssh.close()
BIN
View File
Binary file not shown.
+122
View File
@@ -0,0 +1,122 @@
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int count_threes(int *array, int size) {
int count = 0;
for (int i = 0; i < size; i++) {
if (array[i] == 3) {
count++;
}
}
return count;
}
/**
* @brief Function to generate a random array to test our count3s function
* @param size The size of the array to be generated
* @param world_rank The rank of the process
* @return int* The pointer to the array or NULL if the process is not
* the master
*/
int *generate_array(int size, int world_rank) {
if (world_rank == 0) {
int *array = (int *)malloc(size * sizeof(int));
srand(time(NULL));
for (int i = 0; i < size; i++) {
array[i] = rand() % 3 + 1;
}
return array;
} else {
return NULL;
}
}
int main(int argc, char **argv) {
// Initialize the MPI environment
MPI_Init(&argc, &argv);
// Get the number of processes and the rank of this process
int world_size, world_rank;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
// record start time
double start_time, end_time;
if (world_rank == 0) {
start_time = MPI_Wtime();
}
// Parse command line arguments for array size
if (argc != 2) {
if (world_rank == 0) {
fprintf(stderr, "Usage: %s <size of array>\n", argv[0]);
}
MPI_Finalize();
return 1;
}
int array_size = atoi(argv[1]);
// Allocate and initialize the array
int *array = generate_array(array_size, world_rank);
// Determine the size of the subarray for each process
int subarray_size = array_size / world_size;
// Allocate space for the subarray
int *subarray = (int *)malloc(subarray_size * sizeof(int));
// Scatter the array to all processes
MPI_Scatter(
array,
subarray_size,
MPI_INT,
subarray,
subarray_size,
MPI_INT,
0,
MPI_COMM_WORLD
);
// Each process counts threes in its segment
int local_count = count_threes(subarray, subarray_size);
// Gather the counts from all processes
int total_count = 0;
MPI_Reduce(
&local_count,
&total_count,
1,
MPI_INT,
MPI_SUM,
0,
MPI_COMM_WORLD
);
// Master process prints the total count
if (world_rank == 0) {
printf("Total count of threes: %d\n", total_count);
}
// Clean up
if (world_rank == 0) {
free(array);
}
free(subarray);
// record end time
if (world_rank == 0) {
end_time = MPI_Wtime();
printf(
"Total computation time: %f seconds\n",
end_time - start_time
);
}
// Finalize the MPI environment
MPI_Finalize();
return 0;
}
+4
View File
@@ -0,0 +1,4 @@
kraken
gojiro
tsunami
kaiju
+60
View File
@@ -0,0 +1,60 @@
import paramiko
import os
# Read the input file with the list of hosts, username, and password
import argparse
import paramiko
parser = argparse.ArgumentParser(
description="Configure passwordless ssh for remote hosts"
)
parser.add_argument(
"input_file", type=str, help="path to input file with list of hosts"
)
parser.add_argument("username", type=str, help="username for remote hosts")
parser.add_argument("password", type=str, help="password for remote hosts")
args = parser.parse_args()
with open(args.input_file, "r") as f:
hosts = [line.strip().split()[0] for line in f]
print(hosts)
# For each host in the list, configure ssh key for passwordless ssh
for host in hosts:
# Create a new SSH client
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connect to the remote host
client.connect(host, username=args.username, password=args.password)
print("Connected to", host)
# Generate an ssh key pair on the remote host
stdin, stdout, stderr = client.exec_command(
'echo -e "y\n" | ssh-keygen -q -t rsa -N "" -f ~/.ssh/id_rsa'
)
print("Generated ssh key pair on", host)
stdout.channel.recv_exit_status()
print("Copying public key to authorized_keys on", host)
# Copy the public key to the remote host's authorized_keys file
stdin, stdout, stderr = client.exec_command(
"cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys"
)
print("Copied public key to authorized_keys on", host)
stdout.channel.recv_exit_status()
# Disconnect from the remote host
client.close()
print("Disconnected from", host)
# Test the ssh connection to the remote host
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username=args.username, key_filename=os.path.expanduser("~/.ssh/id_rsa"))
stdin, stdout, stderr = client.exec_command("echo success")
if stdout.read().decode().strip() == "success":
print(f"Successfully configured passwordless ssh for {host}")
else:
print(f"Error configuring passwordless ssh for {host}")
client.close()
+550
View File
@@ -0,0 +1,550 @@
# SPDX-License-Identifier: GPL-2.0
#
# clang-format configuration file. Intended for clang-format >= 4.
#
# For more information, see:
#
# Documentation/process/clang-format.rst
# https://clang.llvm.org/docs/ClangFormat.html
# https://clang.llvm.org/docs/ClangFormatStyleOptions.html
#
---
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Left # Unknown to clang-format-4.0
AlignOperands: true
AlignTrailingComments: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: true
AfterNamespace: true
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false # Unknown to clang-format-5.0
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: true # Unknown to clang-format-4.0
SplitEmptyRecord: true # Unknown to clang-format-4.0
SplitEmptyNamespace: true # Unknown to clang-format-4.0
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Custom
BreakBeforeInheritanceComma: false # Unknown to clang-format-4.0
BreakBeforeTernaryOperators: false
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeComma # Unknown to clang-format-4.0
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: false
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false # Unknown to clang-format-4.0
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 8
ContinuationIndentWidth: 8
Cpp11BracedListStyle: false
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: false # Unknown to clang-format-4.0
# Taken from:
# git grep -h '^#define [^[:space:]]*for_each[^[:space:]]*(' include/ \
# | sed "s,^#define \([^[:space:]]*for_each[^[:space:]]*\)(.*$, - '\1'," \
# | sort | uniq
ForEachMacros:
- 'apei_estatus_for_each_section'
- 'ata_for_each_dev'
- 'ata_for_each_link'
- '__ata_qc_for_each'
- 'ata_qc_for_each'
- 'ata_qc_for_each_raw'
- 'ata_qc_for_each_with_internal'
- 'ax25_for_each'
- 'ax25_uid_for_each'
- '__bio_for_each_bvec'
- 'bio_for_each_bvec'
- 'bio_for_each_bvec_all'
- 'bio_for_each_integrity_vec'
- '__bio_for_each_segment'
- 'bio_for_each_segment'
- 'bio_for_each_segment_all'
- 'bio_list_for_each'
- 'bip_for_each_vec'
- 'bitmap_for_each_clear_region'
- 'bitmap_for_each_set_region'
- 'blkg_for_each_descendant_post'
- 'blkg_for_each_descendant_pre'
- 'blk_queue_for_each_rl'
- 'bond_for_each_slave'
- 'bond_for_each_slave_rcu'
- 'bpf_for_each_spilled_reg'
- 'btree_for_each_safe128'
- 'btree_for_each_safe32'
- 'btree_for_each_safe64'
- 'btree_for_each_safel'
- 'card_for_each_dev'
- 'cgroup_taskset_for_each'
- 'cgroup_taskset_for_each_leader'
- 'cpufreq_for_each_entry'
- 'cpufreq_for_each_entry_idx'
- 'cpufreq_for_each_valid_entry'
- 'cpufreq_for_each_valid_entry_idx'
- 'css_for_each_child'
- 'css_for_each_descendant_post'
- 'css_for_each_descendant_pre'
- 'device_for_each_child_node'
- 'dma_fence_chain_for_each'
- 'do_for_each_ftrace_op'
- 'drm_atomic_crtc_for_each_plane'
- 'drm_atomic_crtc_state_for_each_plane'
- 'drm_atomic_crtc_state_for_each_plane_state'
- 'drm_atomic_for_each_plane_damage'
- 'drm_client_for_each_connector_iter'
- 'drm_client_for_each_modeset'
- 'drm_connector_for_each_possible_encoder'
- 'drm_for_each_bridge_in_chain'
- 'drm_for_each_connector_iter'
- 'drm_for_each_crtc'
- 'drm_for_each_crtc_reverse'
- 'drm_for_each_encoder'
- 'drm_for_each_encoder_mask'
- 'drm_for_each_fb'
- 'drm_for_each_legacy_plane'
- 'drm_for_each_plane'
- 'drm_for_each_plane_mask'
- 'drm_for_each_privobj'
- 'drm_mm_for_each_hole'
- 'drm_mm_for_each_node'
- 'drm_mm_for_each_node_in_range'
- 'drm_mm_for_each_node_safe'
- 'flow_action_for_each'
- 'for_each_active_dev_scope'
- 'for_each_active_drhd_unit'
- 'for_each_active_iommu'
- 'for_each_aggr_pgid'
- 'for_each_available_child_of_node'
- 'for_each_bio'
- 'for_each_board_func_rsrc'
- 'for_each_bvec'
- 'for_each_card_auxs'
- 'for_each_card_auxs_safe'
- 'for_each_card_components'
- 'for_each_card_dapms'
- 'for_each_card_pre_auxs'
- 'for_each_card_prelinks'
- 'for_each_card_rtds'
- 'for_each_card_rtds_safe'
- 'for_each_card_widgets'
- 'for_each_card_widgets_safe'
- 'for_each_cgroup_storage_type'
- 'for_each_child_of_node'
- 'for_each_clear_bit'
- 'for_each_clear_bit_from'
- 'for_each_cmsghdr'
- 'for_each_compatible_node'
- 'for_each_component_dais'
- 'for_each_component_dais_safe'
- 'for_each_comp_order'
- 'for_each_console'
- 'for_each_cpu'
- 'for_each_cpu_and'
- 'for_each_cpu_not'
- 'for_each_cpu_wrap'
- 'for_each_dapm_widgets'
- 'for_each_dev_addr'
- 'for_each_dev_scope'
- 'for_each_displayid_db'
- 'for_each_dma_cap_mask'
- 'for_each_dpcm_be'
- 'for_each_dpcm_be_rollback'
- 'for_each_dpcm_be_safe'
- 'for_each_dpcm_fe'
- 'for_each_drhd_unit'
- 'for_each_dss_dev'
- 'for_each_efi_memory_desc'
- 'for_each_efi_memory_desc_in_map'
- 'for_each_element'
- 'for_each_element_extid'
- 'for_each_element_id'
- 'for_each_endpoint_of_node'
- 'for_each_evictable_lru'
- 'for_each_fib6_node_rt_rcu'
- 'for_each_fib6_walker_rt'
- 'for_each_free_mem_pfn_range_in_zone'
- 'for_each_free_mem_pfn_range_in_zone_from'
- 'for_each_free_mem_range'
- 'for_each_free_mem_range_reverse'
- 'for_each_func_rsrc'
- 'for_each_hstate'
- 'for_each_if'
- 'for_each_iommu'
- 'for_each_ip_tunnel_rcu'
- 'for_each_irq_nr'
- 'for_each_link_codecs'
- 'for_each_link_cpus'
- 'for_each_link_platforms'
- 'for_each_lru'
- 'for_each_matching_node'
- 'for_each_matching_node_and_match'
- 'for_each_member'
- 'for_each_memcg_cache_index'
- 'for_each_mem_pfn_range'
- '__for_each_mem_range'
- 'for_each_mem_range'
- '__for_each_mem_range_rev'
- 'for_each_mem_range_rev'
- 'for_each_mem_region'
- 'for_each_migratetype_order'
- 'for_each_msi_entry'
- 'for_each_msi_entry_safe'
- 'for_each_net'
- 'for_each_net_continue_reverse'
- 'for_each_netdev'
- 'for_each_netdev_continue'
- 'for_each_netdev_continue_rcu'
- 'for_each_netdev_continue_reverse'
- 'for_each_netdev_feature'
- 'for_each_netdev_in_bond_rcu'
- 'for_each_netdev_rcu'
- 'for_each_netdev_reverse'
- 'for_each_netdev_safe'
- 'for_each_net_rcu'
- 'for_each_new_connector_in_state'
- 'for_each_new_crtc_in_state'
- 'for_each_new_mst_mgr_in_state'
- 'for_each_new_plane_in_state'
- 'for_each_new_private_obj_in_state'
- 'for_each_node'
- 'for_each_node_by_name'
- 'for_each_node_by_type'
- 'for_each_node_mask'
- 'for_each_node_state'
- 'for_each_node_with_cpus'
- 'for_each_node_with_property'
- 'for_each_nonreserved_multicast_dest_pgid'
- 'for_each_of_allnodes'
- 'for_each_of_allnodes_from'
- 'for_each_of_cpu_node'
- 'for_each_of_pci_range'
- 'for_each_old_connector_in_state'
- 'for_each_old_crtc_in_state'
- 'for_each_old_mst_mgr_in_state'
- 'for_each_oldnew_connector_in_state'
- 'for_each_oldnew_crtc_in_state'
- 'for_each_oldnew_mst_mgr_in_state'
- 'for_each_oldnew_plane_in_state'
- 'for_each_oldnew_plane_in_state_reverse'
- 'for_each_oldnew_private_obj_in_state'
- 'for_each_old_plane_in_state'
- 'for_each_old_private_obj_in_state'
- 'for_each_online_cpu'
- 'for_each_online_node'
- 'for_each_online_pgdat'
- 'for_each_pci_bridge'
- 'for_each_pci_dev'
- 'for_each_pci_msi_entry'
- 'for_each_pcm_streams'
- 'for_each_physmem_range'
- 'for_each_populated_zone'
- 'for_each_possible_cpu'
- 'for_each_present_cpu'
- 'for_each_prime_number'
- 'for_each_prime_number_from'
- 'for_each_process'
- 'for_each_process_thread'
- 'for_each_property_of_node'
- 'for_each_registered_fb'
- 'for_each_requested_gpio'
- 'for_each_requested_gpio_in_range'
- 'for_each_reserved_mem_range'
- 'for_each_reserved_mem_region'
- 'for_each_rtd_codec_dais'
- 'for_each_rtd_components'
- 'for_each_rtd_cpu_dais'
- 'for_each_rtd_dais'
- 'for_each_set_bit'
- 'for_each_set_bit_from'
- 'for_each_set_clump8'
- 'for_each_sg'
- 'for_each_sg_dma_page'
- 'for_each_sg_page'
- 'for_each_sgtable_dma_page'
- 'for_each_sgtable_dma_sg'
- 'for_each_sgtable_page'
- 'for_each_sgtable_sg'
- 'for_each_sibling_event'
- 'for_each_subelement'
- 'for_each_subelement_extid'
- 'for_each_subelement_id'
- '__for_each_thread'
- 'for_each_thread'
- 'for_each_unicast_dest_pgid'
- 'for_each_vsi'
- 'for_each_wakeup_source'
- 'for_each_zone'
- 'for_each_zone_zonelist'
- 'for_each_zone_zonelist_nodemask'
- 'fwnode_for_each_available_child_node'
- 'fwnode_for_each_child_node'
- 'fwnode_graph_for_each_endpoint'
- 'gadget_for_each_ep'
- 'genradix_for_each'
- 'genradix_for_each_from'
- 'hash_for_each'
- 'hash_for_each_possible'
- 'hash_for_each_possible_rcu'
- 'hash_for_each_possible_rcu_notrace'
- 'hash_for_each_possible_safe'
- 'hash_for_each_rcu'
- 'hash_for_each_safe'
- 'hctx_for_each_ctx'
- 'hlist_bl_for_each_entry'
- 'hlist_bl_for_each_entry_rcu'
- 'hlist_bl_for_each_entry_safe'
- 'hlist_for_each'
- 'hlist_for_each_entry'
- 'hlist_for_each_entry_continue'
- 'hlist_for_each_entry_continue_rcu'
- 'hlist_for_each_entry_continue_rcu_bh'
- 'hlist_for_each_entry_from'
- 'hlist_for_each_entry_from_rcu'
- 'hlist_for_each_entry_rcu'
- 'hlist_for_each_entry_rcu_bh'
- 'hlist_for_each_entry_rcu_notrace'
- 'hlist_for_each_entry_safe'
- 'hlist_for_each_entry_srcu'
- '__hlist_for_each_rcu'
- 'hlist_for_each_safe'
- 'hlist_nulls_for_each_entry'
- 'hlist_nulls_for_each_entry_from'
- 'hlist_nulls_for_each_entry_rcu'
- 'hlist_nulls_for_each_entry_safe'
- 'i3c_bus_for_each_i2cdev'
- 'i3c_bus_for_each_i3cdev'
- 'ide_host_for_each_port'
- 'ide_port_for_each_dev'
- 'ide_port_for_each_present_dev'
- 'idr_for_each_entry'
- 'idr_for_each_entry_continue'
- 'idr_for_each_entry_continue_ul'
- 'idr_for_each_entry_ul'
- 'in_dev_for_each_ifa_rcu'
- 'in_dev_for_each_ifa_rtnl'
- 'inet_bind_bucket_for_each'
- 'inet_lhash2_for_each_icsk_rcu'
- 'key_for_each'
- 'key_for_each_safe'
- 'klp_for_each_func'
- 'klp_for_each_func_safe'
- 'klp_for_each_func_static'
- 'klp_for_each_object'
- 'klp_for_each_object_safe'
- 'klp_for_each_object_static'
- 'kunit_suite_for_each_test_case'
- 'kvm_for_each_memslot'
- 'kvm_for_each_vcpu'
- 'list_for_each'
- 'list_for_each_codec'
- 'list_for_each_codec_safe'
- 'list_for_each_continue'
- 'list_for_each_entry'
- 'list_for_each_entry_continue'
- 'list_for_each_entry_continue_rcu'
- 'list_for_each_entry_continue_reverse'
- 'list_for_each_entry_from'
- 'list_for_each_entry_from_rcu'
- 'list_for_each_entry_from_reverse'
- 'list_for_each_entry_lockless'
- 'list_for_each_entry_rcu'
- 'list_for_each_entry_reverse'
- 'list_for_each_entry_safe'
- 'list_for_each_entry_safe_continue'
- 'list_for_each_entry_safe_from'
- 'list_for_each_entry_safe_reverse'
- 'list_for_each_entry_srcu'
- 'list_for_each_prev'
- 'list_for_each_prev_safe'
- 'list_for_each_safe'
- 'llist_for_each'
- 'llist_for_each_entry'
- 'llist_for_each_entry_safe'
- 'llist_for_each_safe'
- 'mci_for_each_dimm'
- 'media_device_for_each_entity'
- 'media_device_for_each_intf'
- 'media_device_for_each_link'
- 'media_device_for_each_pad'
- 'nanddev_io_for_each_page'
- 'netdev_for_each_lower_dev'
- 'netdev_for_each_lower_private'
- 'netdev_for_each_lower_private_rcu'
- 'netdev_for_each_mc_addr'
- 'netdev_for_each_uc_addr'
- 'netdev_for_each_upper_dev_rcu'
- 'netdev_hw_addr_list_for_each'
- 'nft_rule_for_each_expr'
- 'nla_for_each_attr'
- 'nla_for_each_nested'
- 'nlmsg_for_each_attr'
- 'nlmsg_for_each_msg'
- 'nr_neigh_for_each'
- 'nr_neigh_for_each_safe'
- 'nr_node_for_each'
- 'nr_node_for_each_safe'
- 'of_for_each_phandle'
- 'of_property_for_each_string'
- 'of_property_for_each_u32'
- 'pci_bus_for_each_resource'
- 'pcl_for_each_chunk'
- 'pcl_for_each_segment'
- 'pcm_for_each_format'
- 'ping_portaddr_for_each_entry'
- 'plist_for_each'
- 'plist_for_each_continue'
- 'plist_for_each_entry'
- 'plist_for_each_entry_continue'
- 'plist_for_each_entry_safe'
- 'plist_for_each_safe'
- 'pnp_for_each_card'
- 'pnp_for_each_dev'
- 'protocol_for_each_card'
- 'protocol_for_each_dev'
- 'queue_for_each_hw_ctx'
- 'radix_tree_for_each_slot'
- 'radix_tree_for_each_tagged'
- 'rbtree_postorder_for_each_entry_safe'
- 'rdma_for_each_block'
- 'rdma_for_each_port'
- 'rdma_umem_for_each_dma_block'
- 'resource_list_for_each_entry'
- 'resource_list_for_each_entry_safe'
- 'rhl_for_each_entry_rcu'
- 'rhl_for_each_rcu'
- 'rht_for_each'
- 'rht_for_each_entry'
- 'rht_for_each_entry_from'
- 'rht_for_each_entry_rcu'
- 'rht_for_each_entry_rcu_from'
- 'rht_for_each_entry_safe'
- 'rht_for_each_from'
- 'rht_for_each_rcu'
- 'rht_for_each_rcu_from'
- '__rq_for_each_bio'
- 'rq_for_each_bvec'
- 'rq_for_each_segment'
- 'scsi_for_each_prot_sg'
- 'scsi_for_each_sg'
- 'sctp_for_each_hentry'
- 'sctp_skb_for_each'
- 'shdma_for_each_chan'
- '__shost_for_each_device'
- 'shost_for_each_device'
- 'sk_for_each'
- 'sk_for_each_bound'
- 'sk_for_each_entry_offset_rcu'
- 'sk_for_each_from'
- 'sk_for_each_rcu'
- 'sk_for_each_safe'
- 'sk_nulls_for_each'
- 'sk_nulls_for_each_from'
- 'sk_nulls_for_each_rcu'
- 'snd_array_for_each'
- 'snd_pcm_group_for_each_entry'
- 'snd_soc_dapm_widget_for_each_path'
- 'snd_soc_dapm_widget_for_each_path_safe'
- 'snd_soc_dapm_widget_for_each_sink_path'
- 'snd_soc_dapm_widget_for_each_source_path'
- 'tb_property_for_each'
- 'tcf_exts_for_each_action'
- 'udp_portaddr_for_each_entry'
- 'udp_portaddr_for_each_entry_rcu'
- 'usb_hub_for_each_child'
- 'v4l2_device_for_each_subdev'
- 'v4l2_m2m_for_each_dst_buf'
- 'v4l2_m2m_for_each_dst_buf_safe'
- 'v4l2_m2m_for_each_src_buf'
- 'v4l2_m2m_for_each_src_buf_safe'
- 'virtio_device_for_each_vq'
- 'while_for_each_ftrace_op'
- 'xa_for_each'
- 'xa_for_each_marked'
- 'xa_for_each_range'
- 'xa_for_each_start'
- 'xas_for_each'
- 'xas_for_each_conflict'
- 'xas_for_each_marked'
- 'xbc_array_for_each_value'
- 'xbc_for_each_key_value'
- 'xbc_node_for_each_array_value'
- 'xbc_node_for_each_child'
- 'xbc_node_for_each_key_value'
- 'zorro_for_each_dev'
IncludeBlocks: Preserve # Unknown to clang-format-5.0
IncludeCategories:
- Regex: '.*'
Priority: 1
IncludeIsMainRegex: '(Test)?$'
IndentCaseLabels: false
IndentPPDirectives: None # Unknown to clang-format-5.0
IndentWidth: 8
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Auto # Unknown to clang-format-5.0
ObjCBlockIndentWidth: 8
ObjCSpaceAfterProperty: true
ObjCSpaceBeforeProtocolList: true
# Taken from git's rules
PenaltyBreakAssignment: 10 # Unknown to clang-format-4.0
PenaltyBreakBeforeFirstCallParameter: 30
PenaltyBreakComment: 10
PenaltyBreakFirstLessLess: 0
PenaltyBreakString: 10
PenaltyExcessCharacter: 100
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
ReflowComments: false
SortIncludes: false
SortUsingDeclarations: false # Unknown to clang-format-4.0
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCtorInitializerColon: true # Unknown to clang-format-5.0
SpaceBeforeInheritanceColon: true # Unknown to clang-format-5.0
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true # Unknown to clang-format-5.0
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInContainerLiterals: false
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp03
TabWidth: 8
UseTab: false
+7
View File
@@ -0,0 +1,7 @@
all: padded
padded: padded.c
gcc -O0 -Wall -Werror -Wextra -pedantic -pthread -lpthread -o padded padded.c
clean:
rm -rf padded
BIN
View File
Binary file not shown.
+171
View File
@@ -0,0 +1,171 @@
// Ziad Arafat
// Created: 03/12/2023
// Figure 1.11 in the textbook
/**
* @brief This program will create an array of a specified size and fill it
* with random numbers between 1 and 3 inclusive. It will then try to count
* the number of threes in the array using a serial method and a parallel method
* it will return the counts for each attempt as well as the running times.
*
* In this version we will create a struct called padded_int which will contain
* the count as well as a padding of chars set to fill up the chache line of
* the maching we run it on.
*
* In this revised version we will use as much functional programming principles
* as reasonable to make the code more readable and maintainable.
*/
#define DEBUG 0 // flag to print debug values
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#define MAX_PADDING_SIZE 64 // Max cache line size
typedef struct {
int value;
char padding[MAX_PADDING_SIZE - sizeof(int)];
} padded_int;
typedef struct {
int index;
int segment_size;
int array_size;
int *array;
} thread_args_t;
/**
* @brief Function to generate a random array to test our count3s function
* @param size The size of the array to be generated
* @return int* The pointer to the array
*/
int* generate_array(int size) {
int* array = (int*) malloc(size * sizeof(int));
srand(time(NULL));
for (int i = 0; i < size; i++) {
array[i] = rand() % 3 + 1;
}
return array;
}
/**
* @brief Function to count the number of threes in an array
* @param array The array to be counted
* @param start The starting index of the array to be counted
* @param end The ending index of the array to be counted
* @return int The number of threes in the array
*/
int count_3s_in_segment(int* array, int start, int end) {
int count = 0;
for (int i = start; i < end; i++) {
if (array[i] == 3) {
count++;
}
}
return count;
}
/**
* @brief Thread function to count the number of threes in an array
* @param arg The arguments to be passed to the thread
* @return void* The number of threes in the array
*/
void* count_3s_thread(void* thread_args) {
thread_args_t *args = (thread_args_t *) thread_args;
int start = args->index * args->segment_size;
int end = (args->index == args->array_size / args->segment_size - 1) ? args->array_size : start + args->segment_size;
// count threes
int count = 0;
for (int i = start; i < end; i++) {
if (args->array[i] == 3) {
count++;
}
}
padded_int *result = (padded_int *) malloc(sizeof(padded_int));
result->value = count;
return (void *) result;
}
/**
* @brief Function to count the number of threes by spawning threads and
* collecting the results.
* @param array The array to be counted
* @param size The size of the array to be counted
* @param num_threads The number of threads to be spawned
* @return long The time taken to count the number of threes
*/
long count_3s_parallel(int* array, int size, int num_threads) {
struct timespec start, end;
pthread_t threads[num_threads];
thread_args_t thread_args[num_threads];
long total_threes = 0;
int segment_size = size / num_threads;
// start timer
clock_gettime(CLOCK_REALTIME, &start);
for (int i = 0 ; i < num_threads; i++) {
thread_args[i].index = i;
thread_args[i].segment_size = segment_size;
thread_args[i].array_size = size;
thread_args[i].array = array;
pthread_create(
&threads[i],
NULL,
count_3s_thread,
(void *) &thread_args[i]
);
}
for (int i = 0; i < num_threads; i++) {
padded_int *result;
pthread_join(threads[i], (void **) &result);
total_threes += result->value;
free(result);
}
// end timer
clock_gettime(CLOCK_REALTIME, &end);
// calculate the elapsed time in nanoseconds
long elapsed_time = (end.tv_sec - start.tv_sec) * 1000000000 + end.tv_nsec - start.tv_nsec;
return elapsed_time;
}
int main(int argc, char **argv) {
if (argc != 3) {
printf("Usage: %s <array_size> <num_threads>\n", argv[0]);
return 1;
}
srand((unsigned int) time(NULL));
int array_size = atoi(argv[1]);
int num_threads = atoi(argv[2]);
int *array = generate_array(array_size);
long parallel_time = count_3s_parallel(array, array_size, num_threads);
free(array);
printf("parallel time: %ld\n", parallel_time);
return 0;
}
+14
View File
@@ -0,0 +1,14 @@
"""This script will test all the implementations of count_threes
and record the running times of each implementation. Each implementation
will be tested on sizes of 10000, 100000, 1000000, 10000000. It will be run
5 times each and the average will be taken. The results will be saved to a csv.
The implementations are C programs and a Java Program contained in subfolders.
Each one has a makefile to compile it and can be run from the command line as
follows:
$ make
$ ./count_threes
"""
import time
import csv