Commits

Kota UENISHI  committed 9ebdf3d

add __sync_fetch_and_add test code

  • Participants
  • Parent commits 8ef6644

Comments (0)

Files changed (1)

File c/atomic_ops.c

+#include <stdio.h>
+#include <pthread.h>
+#include <sys/time.h>
+
+volatile unsigned long long counter;
+const size_t N=1024*1024;
+const size_t thread_num=1024;
+
+void* inc(void* ptr) {
+  size_t i=0;
+  printf("start\n");
+  for(i=0;i<N;++i){
+    __sync_fetch_and_add(&counter, 1);
+  }
+  return NULL;
+}
+
+int main(int args, char ** argv){
+  size_t i,n=0;
+  pthread_t threads[thread_num];
+  struct timeval start, end;
+  gettimeofday(&start, NULL);
+  for(i=0;i<thread_num;++i){
+    int r = pthread_create(&threads[i], NULL, inc, NULL);
+    if(r!=0){
+      printf("fail\n");
+      return r;
+    }
+  }
+  for(i=0;i<thread_num;++i){
+    int r = pthread_join(threads[i], NULL);
+    if(r!=0){
+      printf("fail2\n");
+      return r;
+    }
+  }
+  gettimeofday(&end, NULL);
+  printf("N * n: %lu\n", thread_num * N);
+  printf("counter: %llu\n", counter);
+  printf("thruput: %f\n",
+         counter / ((end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1000000.0));
+  return 0;
+}