fork download
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <time.h>
  4.  
  5. #define NUM_THREADS 4
  6. #define ITERATIONS 1000000
  7.  
  8. typedef struct {
  9. long value;
  10. char padding[64]; // avoid false sharing
  11. } counter_t;
  12.  
  13. counter_t counters[NUM_THREADS];
  14.  
  15. void* increment(void* arg) {
  16. int id = *(int*)arg;
  17. for (int i = 0; i < ITERATIONS; i++) {
  18. counters[id].value++;
  19. }
  20. return NULL;
  21. }
  22.  
  23. int main() {
  24. pthread_t threads[NUM_THREADS];
  25. int ids[NUM_THREADS];
  26.  
  27. clock_t start = clock();
  28.  
  29. for (int i = 0; i < NUM_THREADS; i++) {
  30. ids[i] = i;
  31. pthread_create(&threads[i], NULL, increment, &ids[i]);
  32. }
  33.  
  34. for (int i = 0; i < NUM_THREADS; i++) {
  35. pthread_join(threads[i], NULL);
  36. }
  37.  
  38. clock_t end = clock();
  39.  
  40. printf("Time (optimized): %f seconds\n",
  41. (double)(end - start) / CLOCKS_PER_SEC);
  42.  
  43. return 0;
  44. }
Success #stdin #stdout 0s 5292KB
stdin
Standard input is empty
stdout
Time (optimized): 0.000519 seconds