-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathutil.cpp
135 lines (108 loc) · 2.42 KB
/
util.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <stdio.h>
#include <stdlib.h>
#include "util.h"
#include "macro.h"
// handle input
void parseParmeter(int argc, char *argv[], int *n, int *k, char *inputFileName){
if(argc < 4 )
{
printf("input must be 3 parameters, such as <./main filename n k>\n");
exit(1);
}
inputFileName = argv[1];
*n = atoi(argv[2]);
*k = atoi(argv[3]);
#ifdef DEBUG
printf("select %d from %d\n", *k, *n);
#endif
}
// read from file
int readFromFile(char *fileName, DATATYPE* data)
{
FILE *fp;
if((fp=fopen(fileName, "r")) == NULL) {
printf("file %s cannot be opened/n", fileName);
exit(1);
}
int i=0;
while(!feof(fp)) {
fscanf(fp, "%f ", &data[i]);
i++;
}
fclose(fp);
return i;
}
// print array
void printArray(DATATYPE* data, int length)
{
for(int i=0; i<length; i++)
printf("%f ", data[i]);
printf("\n");
}
// zero array
void zeroArray(DATATYPE* data, int length)
{
for(int i=0; i<length; i++)
data[i] = 0;
}
#ifdef USE_CPU
// malloc and free on cpu
void* mallocCPUMem(int size)
{
if(size>0)
return malloc(size);
else
return NULL;
}
void freeCPUMem(void *point)
{
if(point != NULL)
free(point);
}
#endif
#ifdef USE_GPU
#include <cuda_runtime.h>
#include <cuda.h>
// malloc and free on cpu
void* mallocGPUMem(int size)
{
if(size<=0)
return NULL;
void* data;
HANDLE_CUDA_ERROR(cudaMalloc(&data, size));
return data;
}
void freeGPUMem(void *point)
{
if(point != NULL)
HANDLE_CUDA_ERROR(cudaFree(point));
}
// copy from cpu to gpu
void cpu2gpu(void *cpudata, void *gpudata, int size)
{
if(size<=0)
return;
HANDLE_CUDA_ERROR(cudaMemcpy(gpudata, cpudata, size, cudaMemcpyHostToDevice));
}
// copy from gpu to cpu
void gpu2cpu(void *gpudata, void *cpudata, int size)
{
if(size<=0)
return;
HANDLE_CUDA_ERROR(cudaMemcpy(cpudata, gpudata, size, cudaMemcpyDeviceToHost));
}
// copy from gpu to gpu
void gpu2gpu(void *gpudata_dest, void *gpudata_src, int size)
{
if(size<=0)
return;
HANDLE_CUDA_ERROR(cudaMemcpy(gpudata_dest, gpudata_src, size, cudaMemcpyDeviceToDevice));
}
// cuda error
void handleCudaError(cudaError_t err, const char *file, int line) {
if (err != cudaSuccess) {
printf( "%s in %s at line %d\n", cudaGetErrorString( err ), file,line );
exit(2);
}
}
#endif