Skip to content

Instantly share code, notes, and snippets.

@LemonDouble
Created April 6, 2018 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save LemonDouble/a173e2d24c826f41c020c73f95fedbae to your computer and use it in GitHub Desktop.
Save LemonDouble/a173e2d24c826f41c020c73f95fedbae to your computer and use it in GitHub Desktop.
//to use standard input/output
#include <iostream>
//to use ofstream
#include <fstream>
//to use thread class
#include <thread>
//to use mutex lock
#include <mutex>
//to use vector
#include <vector>
//to calculate running time
#include <windows.h>
//THREADNUM == number of max thread to calculate
#define THREADNUM 256
using namespace std;
//save data in csv foramt
ofstream out("noLock.csv");
//critical section
static int count = 0;
//mutex lock class
mutex mtx_lock;
//function that increase counter
/*
조건 변화에 따른 내용 구현은 모두 이 함수 안에서 이루어집니다.
*/
void counterIncrease() {
for (int i = 0; i<1000000; i++) {
::count++;
}
}
int main() {
//thread Array to keep threads
vector<thread> threadArr;
int beforeTime = 0;
// increase thread 1 to THREADNUM(==MaxThreads)
for (int nowThread = 1; nowThread <= THREADNUM; nowThread++) {
int sumTime = 0;
//repeat repeatTime Times for each thread
for (int repeatTime = 0; repeatTime < 100; repeatTime++) {
//clear critical section
::count = 0;
//clear thread vector
threadArr.clear();
//init begin Time
int beg = GetTickCount();
//init N threads and push back into threadArray vector
for (int i = 0; i < nowThread; i++) {
threadArr.push_back(thread(&counterIncrease));
}
//wait for all thread finish their work
for (thread & th : threadArr) {
if (th.joinable()) {
th.join();
}
}
//check end time
int end = GetTickCount();
//calculate execution time
int msec = end - beg;
//save execution time
sumTime += msec;
}
//calculate average execution time
int avgTime = sumTime/100;
//print Number of thread & average execution time
cout << "num of thread = " << nowThread << "\t" << "time : " << avgTime << "ms" << "\t";
//print gap compare to before time (n-1 thread execution time) & calculated counter (critical section)
cout << "(" << avgTime - beforeTime <<")"<< "\t" << "count =" << ::count << "\t";
//print if (counter is same as expected == true), else == false
if (::count == nowThread * 1000000) {
cout << "True" << endl;
}
else {
cout << "False" << endl;
}
//also save same data in csv file
out << nowThread << "," << avgTime << "," << avgTime - beforeTime << "," <<::count << ",";
if (::count == nowThread * 1000000) {
out << "True" << endl;
}
else {
out << "False" << endl;
}
beforeTime = avgTime;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment