Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <assert.h>
- #include <iostream>
- #include <pthread.h>
- const int N = 500;
- const int step = 10;
- int n;
- int A[N][N];
- int B[N][N];
- int C[N][N];
- double t1, t2, t3, t4;
- #define num_threads 8
- void* task_code(void* param)
- {
- int num, i, j;
- num = (*((int*)param));
- for (i = num * n / num_threads; i < (num + 1) * n / num_threads; i++)
- for (j = 0; j < n; j++)
- C[i][j] = A[i][j] * B[i][j];
- return NULL;
- }
- double mtime()
- {
- struct timeval t;
- gettimeofday(&t, NULL);
- double mt = (double)t.tv_usec;
- return mt / 1000000;
- }
- int main(void)
- {
- for (int i = 0; i < N; i++) {
- for (int j = 0; j < N; j++) {
- A[i][j] = rand() % 1000;
- B[i][j] = rand() % 1000;
- C[i][j] = 0;
- }
- }
- for (n = step; n <= N; n += step) {
- pthread_t threads[num_threads];
- int thread_args[num_threads];
- int rc, i;
- // ||
- t3 = mtime();
- for (i = 0; i < num_threads; ++i) {
- thread_args[i] = i;
- rc = pthread_create(&threads[i], NULL, task_code, (void*)&thread_args[i]);
- assert(0 == rc);
- }
- for (i = 0; i < num_threads; ++i) {
- rc = pthread_join(threads[i], NULL);
- assert(0 == rc);
- }
- t4 = mtime();
- // default
- t1 = mtime();
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++) {
- C[i][j] = A[i][j] * B[i][j];
- }
- }
- t2 = mtime();
- printf("--------------------------------------------\n");
- printf("n = %d\n", n);
- printf("p = %d\n", num_threads);
- printf("T1 = %lf(s)\n", (t4 - t3));
- printf("Tp = %lf(s)\n", (t2 - t1));
- printf("S = %lf\n", (t2 - t1) / (t4 - t3));
- printf("E = %lf \n", (t2 - t1) / (t4 - t3) / num_threads);
- printf("t1 = %f \n", t1);
- printf("t2 = %f \n", t2);
- printf("t3 = %f \n", t3);
- printf("t4 = %f \n", t4);
- }
- return EXIT_SUCCESS;
- }
- #define WIN32_LEAN_AND_MEAN
- #include <Windows.h>
- #include <stdint.h> // portable: uint64_t MSVC: __int64
- // MSVC defines this in winsock2.h!?
- typedef struct timeval {
- long tv_sec;
- long tv_usec;
- } timeval;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement